|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "log" |
| 6 | + "net/http" |
| 7 | + "os" |
| 8 | + |
| 9 | + "context" |
| 10 | + |
| 11 | + "go.mongodb.org/atlas-sdk/v20231115008/admin" |
| 12 | + |
| 13 | + retryablehttp "github.com/hashicorp/go-retryablehttp" |
| 14 | + "github.com/mongodb-forks/digest" |
| 15 | +) |
| 16 | + |
| 17 | +/* |
| 18 | +* MongoDB Atlas Go SDK Retryable Request Example |
| 19 | +* |
| 20 | +* Example using custom http client that handles rate limiting and 500 Http errors by retrying requests automatically. |
| 21 | +* Example uses https://pkg.go.dev/github.com/hashicorp/go-retryablehttp. |
| 22 | +* Please refer to the package documentation for more information. |
| 23 | + */ |
| 24 | +func main() { |
| 25 | + ctx := context.Background() |
| 26 | + // Values provided as part of env variables |
| 27 | + // See: https://www.mongodb.com/docs/atlas/app-services/authentication/api-key/ |
| 28 | + apiKey := os.Getenv("MONGODB_ATLAS_PUBLIC_KEY") |
| 29 | + apiSecret := os.Getenv("MONGODB_ATLAS_PRIVATE_KEY") |
| 30 | + url := os.Getenv("MONGODB_ATLAS_URL") |
| 31 | + |
| 32 | + // Using custom client |
| 33 | + // This example relies on https://pkg.go.dev/github.com/hashicorp/go-retryablehttp |
| 34 | + // retryablehttp performs automatic retries under certain conditions. |
| 35 | + // Mainly, if an error is returned by the client (connection errors etc), |
| 36 | + /// or if a 500-range response is received, then a retry is invoked. |
| 37 | + retryClient := retryablehttp.NewClient() |
| 38 | + retryClient.RetryMax = 3 |
| 39 | + |
| 40 | + retryableClient, err := newRetryableClient(retryClient, apiKey, apiSecret) |
| 41 | + if err != nil { |
| 42 | + log.Fatal("Cannot instantiate client") |
| 43 | + } |
| 44 | + sdk, err := admin.NewClient( |
| 45 | + admin.UseHTTPClient(retryableClient), |
| 46 | + admin.UseBaseURL(url), |
| 47 | + admin.UseDebug(false)) |
| 48 | + if err != nil { |
| 49 | + log.Fatal(err) |
| 50 | + } |
| 51 | + |
| 52 | + request := sdk.ProjectsApi.ListProjectsWithParams(ctx, |
| 53 | + &admin.ListProjectsApiParams{ |
| 54 | + ItemsPerPage: admin.PtrInt(1), |
| 55 | + IncludeCount: admin.PtrBool(true), |
| 56 | + PageNum: admin.PtrInt(1), |
| 57 | + }) |
| 58 | + projects, _, err := request.Execute() |
| 59 | + if err != nil { |
| 60 | + log.Fatal(err) |
| 61 | + } |
| 62 | + |
| 63 | + fmt.Println("Total Projects", projects.GetTotalCount()) |
| 64 | + |
| 65 | +} |
| 66 | + |
| 67 | +func newRetryableClient(retryClient *retryablehttp.Client, apiKey string, apiSecret string) (*http.Client, error) { |
| 68 | + var transport http.RoundTripper = &retryablehttp.RoundTripper{Client: retryClient} |
| 69 | + digestRetryAbleTransport := digest.NewTransportWithHTTPRoundTripper(apiKey, apiSecret, transport) |
| 70 | + return digestRetryAbleTransport.Client() |
| 71 | +} |
0 commit comments