ParseAPIEnablementError checks if an error is due to a disabled API and extracts the relevant information
(err error)
| 28 | // ParseAPIEnablementError checks if an error is due to a disabled API |
| 29 | // and extracts the relevant information |
| 30 | func ParseAPIEnablementError(err error) *APIEnablementError { |
| 31 | if err == nil { |
| 32 | return nil |
| 33 | } |
| 34 | |
| 35 | errStr := err.Error() |
| 36 | |
| 37 | // Check if this is a SERVICE_DISABLED error |
| 38 | if !strings.Contains(errStr, "SERVICE_DISABLED") && !strings.Contains(errStr, "has not been used in project") { |
| 39 | return nil |
| 40 | } |
| 41 | |
| 42 | // Extract activation URL |
| 43 | urlRegex := regexp.MustCompile(`https://console\.developers\.google\.com/apis/api/([^/]+)/overview\?project=(\d+)`) |
| 44 | matches := urlRegex.FindStringSubmatch(errStr) |
| 45 | |
| 46 | if len(matches) < 3 { |
| 47 | // Try alternate URL format |
| 48 | urlRegex = regexp.MustCompile(`https://console\.cloud\.google\.com/apis/api/([^/]+)/overview\?project=(\d+)`) |
| 49 | matches = urlRegex.FindStringSubmatch(errStr) |
| 50 | } |
| 51 | |
| 52 | if len(matches) < 3 { |
| 53 | return nil |
| 54 | } |
| 55 | |
| 56 | apiName := matches[1] |
| 57 | projectID := matches[2] |
| 58 | |
| 59 | // Extract API title if available |
| 60 | titleRegex := regexp.MustCompile(`"serviceTitle":\s*"([^"]+)"`) |
| 61 | titleMatches := titleRegex.FindStringSubmatch(errStr) |
| 62 | apiTitle := apiName |
| 63 | if len(titleMatches) >= 2 { |
| 64 | apiTitle = titleMatches[1] |
| 65 | } |
| 66 | |
| 67 | return &APIEnablementError{ |
| 68 | APIName: apiName, |
| 69 | APITitle: apiTitle, |
| 70 | ProjectID: projectID, |
| 71 | ActivationURL: matches[0], |
| 72 | OriginalError: err, |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // HandleAPIEnablement provides an interactive flow to enable a required API |
| 77 | func HandleAPIEnablement(apiErr *APIEnablementError) error { |
no test coverage detected