diff --git a/access_application.go b/access_application.go index 6413374deb8..0645de12ac3 100644 --- a/access_application.go +++ b/access_application.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "time" @@ -60,18 +62,18 @@ type AccessApplicationDetailResponse struct { // AccessApplications returns all applications within an account. // // API reference: https://api.cloudflare.com/#access-applications-list-access-applications -func (api *API) AccessApplications(accountID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { - return api.accessApplications(accountID, pageOpts, AccountRouteRoot) +func (api *API) AccessApplications(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { + return api.accessApplications(ctx, accountID, pageOpts, AccountRouteRoot) } // ZoneLevelAccessApplications returns all applications within a zone. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-list-access-applications -func (api *API) ZoneLevelAccessApplications(zoneID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { - return api.accessApplications(zoneID, pageOpts, ZoneRouteRoot) +func (api *API) ZoneLevelAccessApplications(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]AccessApplication, ResultInfo, error) { + return api.accessApplications(ctx, zoneID, pageOpts, ZoneRouteRoot) } -func (api *API) accessApplications(id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessApplication, ResultInfo, error) { +func (api *API) accessApplications(ctx context.Context, id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessApplication, ResultInfo, error) { v := url.Values{} if pageOpts.PerPage > 0 { v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) @@ -85,7 +87,7 @@ func (api *API) accessApplications(id string, pageOpts PaginationOptions, routeR uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessApplication{}, ResultInfo{}, err } @@ -103,19 +105,19 @@ func (api *API) accessApplications(id string, pageOpts PaginationOptions, routeR // application ID. // // API reference: https://api.cloudflare.com/#access-applications-access-applications-details -func (api *API) AccessApplication(accountID, applicationID string) (AccessApplication, error) { - return api.accessApplication(accountID, applicationID, AccountRouteRoot) +func (api *API) AccessApplication(ctx context.Context, accountID, applicationID string) (AccessApplication, error) { + return api.accessApplication(ctx, accountID, applicationID, AccountRouteRoot) } // ZoneLevelAccessApplication returns a single zone level application based on the // application ID. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-access-applications-details -func (api *API) ZoneLevelAccessApplication(zoneID, applicationID string) (AccessApplication, error) { - return api.accessApplication(zoneID, applicationID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessApplication(ctx context.Context, zoneID, applicationID string) (AccessApplication, error) { + return api.accessApplication(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) accessApplication(id, applicationID string, routeRoot RouteRoot) (AccessApplication, error) { +func (api *API) accessApplication(ctx context.Context, id, applicationID string, routeRoot RouteRoot) (AccessApplication, error) { uri := fmt.Sprintf( "/%s/%s/access/apps/%s", routeRoot, @@ -123,7 +125,7 @@ func (api *API) accessApplication(id, applicationID string, routeRoot RouteRoot) applicationID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessApplication{}, err } @@ -140,21 +142,21 @@ func (api *API) accessApplication(id, applicationID string, routeRoot RouteRoot) // CreateAccessApplication creates a new access application. // // API reference: https://api.cloudflare.com/#access-applications-create-access-application -func (api *API) CreateAccessApplication(accountID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.createAccessApplication(accountID, accessApplication, AccountRouteRoot) +func (api *API) CreateAccessApplication(ctx context.Context, accountID string, accessApplication AccessApplication) (AccessApplication, error) { + return api.createAccessApplication(ctx, accountID, accessApplication, AccountRouteRoot) } // CreateZoneLevelAccessApplication creates a new zone level access application. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-create-access-application -func (api *API) CreateZoneLevelAccessApplication(zoneID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.createAccessApplication(zoneID, accessApplication, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessApplication(ctx context.Context, zoneID string, accessApplication AccessApplication) (AccessApplication, error) { + return api.createAccessApplication(ctx, zoneID, accessApplication, ZoneRouteRoot) } -func (api *API) createAccessApplication(id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { +func (api *API) createAccessApplication(ctx context.Context, id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { uri := fmt.Sprintf("/%s/%s/access/apps", routeRoot, id) - res, err := api.makeRequest("POST", uri, accessApplication) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessApplication) if err != nil { return AccessApplication{}, err } @@ -171,18 +173,18 @@ func (api *API) createAccessApplication(id string, accessApplication AccessAppli // UpdateAccessApplication updates an existing access application. // // API reference: https://api.cloudflare.com/#access-applications-update-access-application -func (api *API) UpdateAccessApplication(accountID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.updateAccessApplication(accountID, accessApplication, AccountRouteRoot) +func (api *API) UpdateAccessApplication(ctx context.Context, accountID string, accessApplication AccessApplication) (AccessApplication, error) { + return api.updateAccessApplication(ctx, accountID, accessApplication, AccountRouteRoot) } // UpdateZoneLevelAccessApplication updates an existing zone level access application. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-update-access-application -func (api *API) UpdateZoneLevelAccessApplication(zoneID string, accessApplication AccessApplication) (AccessApplication, error) { - return api.updateAccessApplication(zoneID, accessApplication, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessApplication(ctx context.Context, zoneID string, accessApplication AccessApplication) (AccessApplication, error) { + return api.updateAccessApplication(ctx, zoneID, accessApplication, ZoneRouteRoot) } -func (api *API) updateAccessApplication(id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { +func (api *API) updateAccessApplication(ctx context.Context, id string, accessApplication AccessApplication, routeRoot RouteRoot) (AccessApplication, error) { if accessApplication.ID == "" { return AccessApplication{}, errors.Errorf("access application ID cannot be empty") } @@ -194,7 +196,7 @@ func (api *API) updateAccessApplication(id string, accessApplication AccessAppli accessApplication.ID, ) - res, err := api.makeRequest("PUT", uri, accessApplication) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessApplication) if err != nil { return AccessApplication{}, err } @@ -211,18 +213,18 @@ func (api *API) updateAccessApplication(id string, accessApplication AccessAppli // DeleteAccessApplication deletes an access application. // // API reference: https://api.cloudflare.com/#access-applications-delete-access-application -func (api *API) DeleteAccessApplication(accountID, applicationID string) error { - return api.deleteAccessApplication(accountID, applicationID, AccountRouteRoot) +func (api *API) DeleteAccessApplication(ctx context.Context, accountID, applicationID string) error { + return api.deleteAccessApplication(ctx, accountID, applicationID, AccountRouteRoot) } // DeleteZoneLevelAccessApplication deletes a zone level access application. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-delete-access-application -func (api *API) DeleteZoneLevelAccessApplication(zoneID, applicationID string) error { - return api.deleteAccessApplication(zoneID, applicationID, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessApplication(ctx context.Context, zoneID, applicationID string) error { + return api.deleteAccessApplication(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) deleteAccessApplication(id, applicationID string, routeRoot RouteRoot) error { +func (api *API) deleteAccessApplication(ctx context.Context, id, applicationID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/apps/%s", routeRoot, @@ -230,7 +232,7 @@ func (api *API) deleteAccessApplication(id, applicationID string, routeRoot Rout applicationID, ) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -242,19 +244,19 @@ func (api *API) deleteAccessApplication(id, applicationID string, routeRoot Rout // access application. // // API reference: https://api.cloudflare.com/#access-applications-revoke-access-tokens -func (api *API) RevokeAccessApplicationTokens(accountID, applicationID string) error { - return api.revokeAccessApplicationTokens(accountID, applicationID, AccountRouteRoot) +func (api *API) RevokeAccessApplicationTokens(ctx context.Context, accountID, applicationID string) error { + return api.revokeAccessApplicationTokens(ctx, accountID, applicationID, AccountRouteRoot) } // RevokeZoneLevelAccessApplicationTokens revokes tokens associated with a zone level // access application. // // API reference: https://api.cloudflare.com/#zone-level-access-applications-revoke-access-tokens -func (api *API) RevokeZoneLevelAccessApplicationTokens(zoneID, applicationID string) error { - return api.revokeAccessApplicationTokens(zoneID, applicationID, ZoneRouteRoot) +func (api *API) RevokeZoneLevelAccessApplicationTokens(ctx context.Context, zoneID, applicationID string) error { + return api.revokeAccessApplicationTokens(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) revokeAccessApplicationTokens(id string, applicationID string, routeRoot RouteRoot) error { +func (api *API) revokeAccessApplicationTokens(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/revoke-tokens", routeRoot, @@ -262,7 +264,7 @@ func (api *API) revokeAccessApplicationTokens(id string, applicationID string, r applicationID, ) - _, err := api.makeRequest("POST", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) if err != nil { return err } diff --git a/access_application_test.go b/access_application_test.go index 7939203e5a1..16067cbe8d7 100644 --- a/access_application_test.go +++ b/access_application_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestAccessApplications(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -66,7 +67,7 @@ func TestAccessApplications(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps", handler) - actual, _, err := client.AccessApplications(accountID, PaginationOptions{}) + actual, _, err := client.AccessApplications(context.TODO(), accountID, PaginationOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -74,7 +75,7 @@ func TestAccessApplications(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps", handler) - actual, _, err = client.ZoneLevelAccessApplications(zoneID, PaginationOptions{}) + actual, _, err = client.ZoneLevelAccessApplications(context.TODO(), zoneID, PaginationOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -86,7 +87,7 @@ func TestAccessApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -130,7 +131,7 @@ func TestAccessApplication(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err := client.AccessApplication(accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + actual, err := client.AccessApplication(context.TODO(), accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -138,7 +139,7 @@ func TestAccessApplication(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err = client.ZoneLevelAccessApplication(zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + actual, err = client.ZoneLevelAccessApplication(context.TODO(), zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -150,7 +151,7 @@ func TestCreateAccessApplications(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -193,14 +194,11 @@ func TestCreateAccessApplications(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps", handler) - actual, err := client.CreateAccessApplication( - accountID, - AccessApplication{ - Name: "Admin Site", - Domain: "test.example.com/admin", - SessionDuration: "24h", - }, - ) + actual, err := client.CreateAccessApplication(context.TODO(), accountID, AccessApplication{ + Name: "Admin Site", + Domain: "test.example.com/admin", + SessionDuration: "24h", + }) if assert.NoError(t, err) { assert.Equal(t, fullAccessApplication, actual) @@ -208,14 +206,11 @@ func TestCreateAccessApplications(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps", handler) - actual, err = client.CreateZoneLevelAccessApplication( - zoneID, - AccessApplication{ - Name: "Admin Site", - Domain: "test.example.com/admin", - SessionDuration: "24h", - }, - ) + actual, err = client.CreateZoneLevelAccessApplication(context.TODO(), zoneID, AccessApplication{ + Name: "Admin Site", + Domain: "test.example.com/admin", + SessionDuration: "24h", + }) if assert.NoError(t, err) { assert.Equal(t, fullAccessApplication, actual) @@ -227,7 +222,7 @@ func TestUpdateAccessApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -270,10 +265,7 @@ func TestUpdateAccessApplication(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err := client.UpdateAccessApplication( - accountID, - fullAccessApplication, - ) + actual, err := client.UpdateAccessApplication(context.TODO(), accountID, fullAccessApplication) if assert.NoError(t, err) { assert.Equal(t, fullAccessApplication, actual) @@ -281,10 +273,7 @@ func TestUpdateAccessApplication(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err = client.UpdateZoneLevelAccessApplication( - zoneID, - fullAccessApplication, - ) + actual, err = client.UpdateZoneLevelAccessApplication(context.TODO(), zoneID, fullAccessApplication) if assert.NoError(t, err) { assert.Equal(t, fullAccessApplication, actual) @@ -295,10 +284,10 @@ func TestUpdateAccessApplicationWithMissingID(t *testing.T) { setup() defer teardown() - _, err := client.UpdateAccessApplication(zoneID, AccessApplication{}) + _, err := client.UpdateAccessApplication(context.TODO(), zoneID, AccessApplication{}) assert.EqualError(t, err, "access application ID cannot be empty") - _, err = client.UpdateZoneLevelAccessApplication(zoneID, AccessApplication{}) + _, err = client.UpdateZoneLevelAccessApplication(context.TODO(), zoneID, AccessApplication{}) assert.EqualError(t, err, "access application ID cannot be empty") } @@ -307,7 +296,7 @@ func TestDeleteAccessApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -321,12 +310,12 @@ func TestDeleteAccessApplication(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - err := client.DeleteAccessApplication(accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + err := client.DeleteAccessApplication(context.TODO(), accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - err = client.DeleteZoneLevelAccessApplication(zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + err = client.DeleteZoneLevelAccessApplication(context.TODO(), zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") assert.NoError(t, err) } @@ -336,7 +325,7 @@ func TestRevokeAccessApplicationTokens(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -347,12 +336,12 @@ func TestRevokeAccessApplicationTokens(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db/revoke-tokens", handler) - err := client.RevokeAccessApplicationTokens(accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + err := client.RevokeAccessApplicationTokens(context.TODO(), accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db/revoke-tokens", handler) - err = client.RevokeZoneLevelAccessApplicationTokens(zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + err = client.RevokeZoneLevelAccessApplicationTokens(context.TODO(), zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") assert.NoError(t, err) } @@ -362,7 +351,7 @@ func TestAccessApplicationWithCORS(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -405,7 +394,7 @@ func TestAccessApplicationWithCORS(t *testing.T) { Domain: "test.example.com/admin", SessionDuration: "24h", CorsHeaders: &AccessApplicationCorsHeaders{ - AllowedMethods: []string{"GET"}, + AllowedMethods: []string{http.MethodGet}, AllowedOrigins: []string{"https://example.com"}, AllowAllHeaders: true, MaxAge: -1, @@ -414,7 +403,7 @@ func TestAccessApplicationWithCORS(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err := client.AccessApplication(accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + actual, err := client.AccessApplication(context.TODO(), accountID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -422,7 +411,7 @@ func TestAccessApplicationWithCORS(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/480f4f69-1a28-4fdd-9240-1ed29f0ac1db", handler) - actual, err = client.ZoneLevelAccessApplication(zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") + actual, err = client.ZoneLevelAccessApplication(context.TODO(), zoneID, "480f4f69-1a28-4fdd-9240-1ed29f0ac1db") if assert.NoError(t, err) { assert.Equal(t, want, actual) diff --git a/access_audit_log.go b/access_audit_log.go index 85d5c3b96c6..fd12e044137 100644 --- a/access_audit_log.go +++ b/access_audit_log.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" "time" @@ -42,10 +44,10 @@ type AccessAuditLogFilterOptions struct { // AccessAuditLogs retrieves all audit logs for the Access service. // // API reference: https://api.cloudflare.com/#access-requests-access-requests-audit -func (api *API) AccessAuditLogs(accountID string, opts AccessAuditLogFilterOptions) ([]AccessAuditLogRecord, error) { +func (api *API) AccessAuditLogs(ctx context.Context, accountID string, opts AccessAuditLogFilterOptions) ([]AccessAuditLogRecord, error) { uri := "/accounts/" + accountID + "/access/logs/access-requests?" + opts.Encode() - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessAuditLogRecord{}, err } diff --git a/access_audit_log_example_test.go b/access_audit_log_example_test.go index 51adce9827f..2ee6e2412f9 100644 --- a/access_audit_log_example_test.go +++ b/access_audit_log_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "encoding/json" "fmt" "log" @@ -15,7 +16,7 @@ func ExampleAPI_AccessAuditLogs() { } filterOpts := cloudflare.AccessAuditLogFilterOptions{} - results, _ := api.AccessAuditLogs("someaccountid", filterOpts) + results, _ := api.AccessAuditLogs(context.TODO(), "someaccountid", filterOpts) for _, record := range results { b, _ := json.Marshal(record) diff --git a/access_audit_log_test.go b/access_audit_log_test.go index 753d68bc7d2..0f300f2be99 100644 --- a/access_audit_log_test.go +++ b/access_audit_log_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestAccessAuditLogs(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -52,7 +53,7 @@ func TestAccessAuditLogs(t *testing.T) { RayID: "187d944c61940c77", }} - actual, err := client.AccessAuditLogs("01a7362d577a6c3019a474fd6f485823", AccessAuditLogFilterOptions{}) + actual, err := client.AccessAuditLogs(context.TODO(), "01a7362d577a6c3019a474fd6f485823", AccessAuditLogFilterOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) diff --git a/access_ca_certificate.go b/access_ca_certificate.go index 7d52c60bcbe..d19765bc2ae 100644 --- a/access_ca_certificate.go +++ b/access_ca_certificate.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "github.com/pkg/errors" ) @@ -32,21 +34,21 @@ type AccessCACertificateResponse struct { // AccessCACertificates returns all CA certificates within Access. // // API reference: https://api.cloudflare.com/#access-short-lived-certificates-list-short-lived-certificates -func (api *API) AccessCACertificates(accountID string) ([]AccessCACertificate, error) { - return api.accessCACertificates(accountID, AccountRouteRoot) +func (api *API) AccessCACertificates(ctx context.Context, accountID string) ([]AccessCACertificate, error) { + return api.accessCACertificates(ctx, accountID, AccountRouteRoot) } // ZoneLevelAccessCACertificates returns all zone level CA certificates within Access. // // API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-list-short-lived-certificates -func (api *API) ZoneLevelAccessCACertificates(zoneID string) ([]AccessCACertificate, error) { - return api.accessCACertificates(zoneID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessCACertificates(ctx context.Context, zoneID string) ([]AccessCACertificate, error) { + return api.accessCACertificates(ctx, zoneID, ZoneRouteRoot) } -func (api *API) accessCACertificates(id string, routeRoot RouteRoot) ([]AccessCACertificate, error) { +func (api *API) accessCACertificates(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessCACertificate, error) { uri := fmt.Sprintf("/%s/%s/access/apps/ca", routeRoot, id) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessCACertificate{}, err } @@ -64,22 +66,22 @@ func (api *API) accessCACertificates(id string, routeRoot RouteRoot) ([]AccessCA // Application. // // API reference: https://api.cloudflare.com/#access-short-lived-certificates-short-lived-certificate-details -func (api *API) AccessCACertificate(accountID, applicationID string) (AccessCACertificate, error) { - return api.accessCACertificate(accountID, applicationID, AccountRouteRoot) +func (api *API) AccessCACertificate(ctx context.Context, accountID, applicationID string) (AccessCACertificate, error) { + return api.accessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) } // ZoneLevelAccessCACertificate returns a single zone level CA certificate associated with an Access // Application. // // API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-short-lived-certificate-details -func (api *API) ZoneLevelAccessCACertificate(zoneID, applicationID string) (AccessCACertificate, error) { - return api.accessCACertificate(zoneID, applicationID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessCACertificate(ctx context.Context, zoneID, applicationID string) (AccessCACertificate, error) { + return api.accessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) accessCACertificate(id string, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { +func (api *API) accessCACertificate(ctx context.Context, id, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { uri := fmt.Sprintf("/%s/%s/access/apps/%s/ca", routeRoot, id, applicationID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessCACertificate{}, err } @@ -97,19 +99,19 @@ func (api *API) accessCACertificate(id string, applicationID string, routeRoot R // Application. // // API reference: https://api.cloudflare.com/#access-short-lived-certificates-create-short-lived-certificate -func (api *API) CreateAccessCACertificate(accountID, applicationID string) (AccessCACertificate, error) { - return api.createAccessCACertificate(accountID, applicationID, AccountRouteRoot) +func (api *API) CreateAccessCACertificate(ctx context.Context, accountID, applicationID string) (AccessCACertificate, error) { + return api.createAccessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) } // CreateZoneLevelAccessCACertificate creates a new zone level CA certificate for an Access // Application. // // API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-create-short-lived-certificate -func (api *API) CreateZoneLevelAccessCACertificate(zoneID string, applicationID string) (AccessCACertificate, error) { - return api.createAccessCACertificate(zoneID, applicationID, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessCACertificate(ctx context.Context, zoneID string, applicationID string) (AccessCACertificate, error) { + return api.createAccessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) createAccessCACertificate(id string, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { +func (api *API) createAccessCACertificate(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) (AccessCACertificate, error) { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/ca", routeRoot, @@ -117,7 +119,7 @@ func (api *API) createAccessCACertificate(id string, applicationID string, route applicationID, ) - res, err := api.makeRequest("POST", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) if err != nil { return AccessCACertificate{}, err } @@ -135,19 +137,19 @@ func (api *API) createAccessCACertificate(id string, applicationID string, route // Access Application. // // API reference: https://api.cloudflare.com/#access-short-lived-certificates-delete-access-certificate -func (api *API) DeleteAccessCACertificate(accountID, applicationID string) error { - return api.deleteAccessCACertificate(accountID, applicationID, AccountRouteRoot) +func (api *API) DeleteAccessCACertificate(ctx context.Context, accountID, applicationID string) error { + return api.deleteAccessCACertificate(ctx, accountID, applicationID, AccountRouteRoot) } // DeleteZoneLevelAccessCACertificate deletes a zone level Access CA certificate on a defined // Access Application. // // API reference: https://api.cloudflare.com/#zone-level-access-short-lived-certificates-delete-access-certificate -func (api *API) DeleteZoneLevelAccessCACertificate(zoneID, applicationID string) error { - return api.deleteAccessCACertificate(zoneID, applicationID, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessCACertificate(ctx context.Context, zoneID, applicationID string) error { + return api.deleteAccessCACertificate(ctx, zoneID, applicationID, ZoneRouteRoot) } -func (api *API) deleteAccessCACertificate(id string, applicationID string, routeRoot RouteRoot) error { +func (api *API) deleteAccessCACertificate(ctx context.Context, id string, applicationID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/ca", routeRoot, @@ -155,7 +157,7 @@ func (api *API) deleteAccessCACertificate(id string, applicationID string, route applicationID, ) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/access_ca_certificate_test.go b/access_ca_certificate_test.go index a33ddc29f53..fddfae2b733 100644 --- a/access_ca_certificate_test.go +++ b/access_ca_certificate_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -13,7 +14,7 @@ func TestAcessCACertificate(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -36,7 +37,7 @@ func TestAcessCACertificate(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - actual, err := client.AccessCACertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err := client.AccessCACertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -44,7 +45,7 @@ func TestAcessCACertificate(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - actual, err = client.ZoneLevelAccessCACertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err = client.ZoneLevelAccessCACertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -56,7 +57,7 @@ func TestAcessCACertificates(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [{ @@ -79,7 +80,7 @@ func TestAcessCACertificates(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/ca", handler) - actual, err := client.AccessCACertificates(accountID) + actual, err := client.AccessCACertificates(context.TODO(), accountID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -87,7 +88,7 @@ func TestAcessCACertificates(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/ca", handler) - actual, err = client.ZoneLevelAccessCACertificates(zoneID) + actual, err = client.ZoneLevelAccessCACertificates(context.TODO(), zoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -99,7 +100,7 @@ func TestCreateAcessCACertificates(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -122,7 +123,7 @@ func TestCreateAcessCACertificates(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - actual, err := client.CreateAccessCACertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err := client.CreateAccessCACertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -130,7 +131,7 @@ func TestCreateAcessCACertificates(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - actual, err = client.CreateZoneLevelAccessCACertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err = client.CreateZoneLevelAccessCACertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -142,7 +143,7 @@ func TestDeleteAcessCACertificates(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -157,13 +158,13 @@ func TestDeleteAcessCACertificates(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - err := client.DeleteAccessCACertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + err := client.DeleteAccessCACertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/apps/f174e90a-fafe-4643-bbbc-4a0ed4fc8415/ca", handler) - err = client.DeleteZoneLevelAccessCACertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + err = client.DeleteZoneLevelAccessCACertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") assert.NoError(t, err) } diff --git a/access_group.go b/access_group.go index 5a260c5ae1b..36002c71665 100644 --- a/access_group.go +++ b/access_group.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "time" @@ -179,18 +181,18 @@ type AccessGroupDetailResponse struct { // AccessGroups returns all access groups for an access application. // // API reference: https://api.cloudflare.com/#access-groups-list-access-groups -func (api *API) AccessGroups(accountID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { - return api.accessGroups(accountID, pageOpts, AccountRouteRoot) +func (api *API) AccessGroups(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { + return api.accessGroups(ctx, accountID, pageOpts, AccountRouteRoot) } // ZoneLevelAccessGroups returns all zone level access groups for an access application. // // API reference: https://api.cloudflare.com/#zone-level-access-groups-list-access-groups -func (api *API) ZoneLevelAccessGroups(zoneID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { - return api.accessGroups(zoneID, pageOpts, ZoneRouteRoot) +func (api *API) ZoneLevelAccessGroups(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]AccessGroup, ResultInfo, error) { + return api.accessGroups(ctx, zoneID, pageOpts, ZoneRouteRoot) } -func (api *API) accessGroups(id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessGroup, ResultInfo, error) { +func (api *API) accessGroups(ctx context.Context, id string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessGroup, ResultInfo, error) { v := url.Values{} if pageOpts.PerPage > 0 { v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) @@ -209,7 +211,7 @@ func (api *API) accessGroups(id string, pageOpts PaginationOptions, routeRoot Ro uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessGroup{}, ResultInfo{}, err } @@ -226,18 +228,18 @@ func (api *API) accessGroups(id string, pageOpts PaginationOptions, routeRoot Ro // AccessGroup returns a single group based on the group ID. // // API reference: https://api.cloudflare.com/#access-groups-access-group-details -func (api *API) AccessGroup(accountID, groupID string) (AccessGroup, error) { - return api.accessGroup(accountID, groupID, AccountRouteRoot) +func (api *API) AccessGroup(ctx context.Context, accountID, groupID string) (AccessGroup, error) { + return api.accessGroup(ctx, accountID, groupID, AccountRouteRoot) } // ZoneLevelAccessGroup returns a single zone level group based on the group ID. // // API reference: https://api.cloudflare.com/#zone-level-access-groups-access-group-details -func (api *API) ZoneLevelAccessGroup(zoneID, groupID string) (AccessGroup, error) { - return api.accessGroup(zoneID, groupID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessGroup(ctx context.Context, zoneID, groupID string) (AccessGroup, error) { + return api.accessGroup(ctx, zoneID, groupID, ZoneRouteRoot) } -func (api *API) accessGroup(id string, groupID string, routeRoot RouteRoot) (AccessGroup, error) { +func (api *API) accessGroup(ctx context.Context, id, groupID string, routeRoot RouteRoot) (AccessGroup, error) { uri := fmt.Sprintf( "/%s/%s/access/groups/%s", routeRoot, @@ -245,7 +247,7 @@ func (api *API) accessGroup(id string, groupID string, routeRoot RouteRoot) (Acc groupID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessGroup{}, err } @@ -262,25 +264,25 @@ func (api *API) accessGroup(id string, groupID string, routeRoot RouteRoot) (Acc // CreateAccessGroup creates a new access group. // // API reference: https://api.cloudflare.com/#access-groups-create-access-group -func (api *API) CreateAccessGroup(accountID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.createAccessGroup(accountID, accessGroup, AccountRouteRoot) +func (api *API) CreateAccessGroup(ctx context.Context, accountID string, accessGroup AccessGroup) (AccessGroup, error) { + return api.createAccessGroup(ctx, accountID, accessGroup, AccountRouteRoot) } // CreateZoneLevelAccessGroup creates a new zone level access group. // // API reference: https://api.cloudflare.com/#zone-level-access-groups-create-access-group -func (api *API) CreateZoneLevelAccessGroup(zoneID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.createAccessGroup(zoneID, accessGroup, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessGroup(ctx context.Context, zoneID string, accessGroup AccessGroup) (AccessGroup, error) { + return api.createAccessGroup(ctx, zoneID, accessGroup, ZoneRouteRoot) } -func (api *API) createAccessGroup(id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { +func (api *API) createAccessGroup(ctx context.Context, id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { uri := fmt.Sprintf( "/%s/%s/access/groups", routeRoot, id, ) - res, err := api.makeRequest("POST", uri, accessGroup) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessGroup) if err != nil { return AccessGroup{}, err } @@ -297,18 +299,18 @@ func (api *API) createAccessGroup(id string, accessGroup AccessGroup, routeRoot // UpdateAccessGroup updates an existing access group. // // API reference: https://api.cloudflare.com/#access-groups-update-access-group -func (api *API) UpdateAccessGroup(accountID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.updateAccessGroup(accountID, accessGroup, AccountRouteRoot) +func (api *API) UpdateAccessGroup(ctx context.Context, accountID string, accessGroup AccessGroup) (AccessGroup, error) { + return api.updateAccessGroup(ctx, accountID, accessGroup, AccountRouteRoot) } // UpdateZoneLevelAccessGroup updates an existing zone level access group. // // API reference: https://api.cloudflare.com/#zone-level-access-groups-update-access-group -func (api *API) UpdateZoneLevelAccessGroup(zoneID string, accessGroup AccessGroup) (AccessGroup, error) { - return api.updateAccessGroup(zoneID, accessGroup, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessGroup(ctx context.Context, zoneID string, accessGroup AccessGroup) (AccessGroup, error) { + return api.updateAccessGroup(ctx, zoneID, accessGroup, ZoneRouteRoot) } -func (api *API) updateAccessGroup(id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { +func (api *API) updateAccessGroup(ctx context.Context, id string, accessGroup AccessGroup, routeRoot RouteRoot) (AccessGroup, error) { if accessGroup.ID == "" { return AccessGroup{}, errors.Errorf("access group ID cannot be empty") } @@ -319,7 +321,7 @@ func (api *API) updateAccessGroup(id string, accessGroup AccessGroup, routeRoot accessGroup.ID, ) - res, err := api.makeRequest("PUT", uri, accessGroup) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessGroup) if err != nil { return AccessGroup{}, err } @@ -336,18 +338,18 @@ func (api *API) updateAccessGroup(id string, accessGroup AccessGroup, routeRoot // DeleteAccessGroup deletes an access group. // // API reference: https://api.cloudflare.com/#access-groups-delete-access-group -func (api *API) DeleteAccessGroup(accountID, groupID string) error { - return api.deleteAccessGroup(accountID, groupID, AccountRouteRoot) +func (api *API) DeleteAccessGroup(ctx context.Context, accountID, groupID string) error { + return api.deleteAccessGroup(ctx, accountID, groupID, AccountRouteRoot) } // DeleteZoneLevelAccessGroup deletes a zone level access group. // // API reference: https://api.cloudflare.com/#zone-level-access-groups-delete-access-group -func (api *API) DeleteZoneLevelAccessGroup(zoneID, groupID string) error { - return api.deleteAccessGroup(zoneID, groupID, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessGroup(ctx context.Context, zoneID, groupID string) error { + return api.deleteAccessGroup(ctx, zoneID, groupID, ZoneRouteRoot) } -func (api *API) deleteAccessGroup(id string, groupID string, routeRoot RouteRoot) error { +func (api *API) deleteAccessGroup(ctx context.Context, id string, groupID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/groups/%s", routeRoot, @@ -355,7 +357,7 @@ func (api *API) deleteAccessGroup(id string, groupID string, routeRoot RouteRoot groupID, ) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/access_group_test.go b/access_group_test.go index cd7d897d801..6e9ad45d88d 100644 --- a/access_group_test.go +++ b/access_group_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -33,7 +34,7 @@ func TestAccessGroups(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -80,7 +81,7 @@ func TestAccessGroups(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/groups", handler) - actual, _, err := client.AccessGroups(accountID, pageOptions) + actual, _, err := client.AccessGroups(context.TODO(), accountID, pageOptions) if assert.NoError(t, err) { assert.Equal(t, []AccessGroup{expectedAccessGroup}, actual) @@ -88,7 +89,7 @@ func TestAccessGroups(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/groups", handler) - actual, _, err = client.ZoneLevelAccessGroups(zoneID, pageOptions) + actual, _, err = client.ZoneLevelAccessGroups(context.TODO(), zoneID, pageOptions) if assert.NoError(t, err) { assert.Equal(t, []AccessGroup{expectedAccessGroup}, actual) @@ -100,7 +101,7 @@ func TestAccessGroup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -139,7 +140,7 @@ func TestAccessGroup(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/groups/"+accessGroupID, handler) - actual, err := client.AccessGroup(accountID, accessGroupID) + actual, err := client.AccessGroup(context.TODO(), accountID, accessGroupID) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) @@ -147,7 +148,7 @@ func TestAccessGroup(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/groups/"+accessGroupID, handler) - actual, err = client.ZoneLevelAccessGroup(zoneID, accessGroupID) + actual, err = client.ZoneLevelAccessGroup(context.TODO(), zoneID, accessGroupID) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) @@ -159,7 +160,7 @@ func TestCreateAccessGroup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -217,10 +218,7 @@ func TestCreateAccessGroup(t *testing.T) { }, } - actual, err := client.CreateAccessGroup( - accountID, - accessGroup, - ) + actual, err := client.CreateAccessGroup(context.TODO(), accountID, accessGroup) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) @@ -228,10 +226,7 @@ func TestCreateAccessGroup(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/groups", handler) - actual, err = client.CreateZoneLevelAccessGroup( - zoneID, - accessGroup, - ) + actual, err = client.CreateZoneLevelAccessGroup(context.TODO(), zoneID, accessGroup) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) @@ -243,7 +238,7 @@ func TestUpdateAccessGroup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -281,14 +276,14 @@ func TestUpdateAccessGroup(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/groups/"+accessGroupID, handler) - actual, err := client.UpdateAccessGroup(accountID, expectedAccessGroup) + actual, err := client.UpdateAccessGroup(context.TODO(), accountID, expectedAccessGroup) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) } mux.HandleFunc("/zones/"+zoneID+"/access/groups/"+accessGroupID, handler) - actual, err = client.UpdateZoneLevelAccessGroup(zoneID, expectedAccessGroup) + actual, err = client.UpdateZoneLevelAccessGroup(context.TODO(), zoneID, expectedAccessGroup) if assert.NoError(t, err) { assert.Equal(t, expectedAccessGroup, actual) @@ -299,10 +294,10 @@ func TestUpdateAccessGroupWithMissingID(t *testing.T) { setup() defer teardown() - _, err := client.UpdateAccessGroup(accountID, AccessGroup{}) + _, err := client.UpdateAccessGroup(context.TODO(), accountID, AccessGroup{}) assert.EqualError(t, err, "access group ID cannot be empty") - _, err = client.UpdateZoneLevelAccessGroup(zoneID, AccessGroup{}) + _, err = client.UpdateZoneLevelAccessGroup(context.TODO(), zoneID, AccessGroup{}) assert.EqualError(t, err, "access group ID cannot be empty") } @@ -311,7 +306,7 @@ func TestDeleteAccessGroup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -325,12 +320,12 @@ func TestDeleteAccessGroup(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/groups/"+accessGroupID, handler) - err := client.DeleteAccessGroup(accountID, accessGroupID) + err := client.DeleteAccessGroup(context.TODO(), accountID, accessGroupID) assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/groups/"+accessGroupID, handler) - err = client.DeleteZoneLevelAccessGroup(zoneID, accessGroupID) + err = client.DeleteZoneLevelAccessGroup(context.TODO(), zoneID, accessGroupID) assert.NoError(t, err) } diff --git a/access_identity_provider.go b/access_identity_provider.go index d12e0ce34a6..5b7cf04144c 100644 --- a/access_identity_provider.go +++ b/access_identity_provider.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "github.com/pkg/errors" ) @@ -60,22 +62,22 @@ type AccessIdentityProviderListResponse struct { // account. // // API reference: https://api.cloudflare.com/#access-identity-providers-list-access-identity-providers -func (api *API) AccessIdentityProviders(accountID string) ([]AccessIdentityProvider, error) { - return api.accessIdentityProviders(accountID, AccountRouteRoot) +func (api *API) AccessIdentityProviders(ctx context.Context, accountID string) ([]AccessIdentityProvider, error) { + return api.accessIdentityProviders(ctx, accountID, AccountRouteRoot) } // ZoneLevelAccessIdentityProviders returns all Access Identity Providers for an // account. // // API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-list-access-identity-providers -func (api *API) ZoneLevelAccessIdentityProviders(zoneID string) ([]AccessIdentityProvider, error) { - return api.accessIdentityProviders(zoneID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessIdentityProviders(ctx context.Context, zoneID string) ([]AccessIdentityProvider, error) { + return api.accessIdentityProviders(ctx, zoneID, ZoneRouteRoot) } -func (api *API) accessIdentityProviders(id string, routeRoot RouteRoot) ([]AccessIdentityProvider, error) { +func (api *API) accessIdentityProviders(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessIdentityProvider, error) { uri := fmt.Sprintf("/%s/%s/access/identity_providers", routeRoot, id) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessIdentityProvider{}, err } @@ -93,19 +95,19 @@ func (api *API) accessIdentityProviders(id string, routeRoot RouteRoot) ([]Acces // Provider for an account. // // API reference: https://api.cloudflare.com/#access-identity-providers-access-identity-providers-details -func (api *API) AccessIdentityProviderDetails(accountID, identityProviderID string) (AccessIdentityProvider, error) { - return api.accessIdentityProviderDetails(accountID, identityProviderID, AccountRouteRoot) +func (api *API) AccessIdentityProviderDetails(ctx context.Context, accountID, identityProviderID string) (AccessIdentityProvider, error) { + return api.accessIdentityProviderDetails(ctx, accountID, identityProviderID, AccountRouteRoot) } // ZoneLevelAccessIdentityProviderDetails returns a single zone level Access Identity // Provider for an account. // // API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-access-identity-providers-details -func (api *API) ZoneLevelAccessIdentityProviderDetails(zoneID, identityProviderID string) (AccessIdentityProvider, error) { - return api.accessIdentityProviderDetails(zoneID, identityProviderID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessIdentityProviderDetails(ctx context.Context, zoneID, identityProviderID string) (AccessIdentityProvider, error) { + return api.accessIdentityProviderDetails(ctx, zoneID, identityProviderID, ZoneRouteRoot) } -func (api *API) accessIdentityProviderDetails(id string, identityProviderID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { +func (api *API) accessIdentityProviderDetails(ctx context.Context, id string, identityProviderID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { uri := fmt.Sprintf( "/%s/%s/access/identity_providers/%s", routeRoot, @@ -113,7 +115,7 @@ func (api *API) accessIdentityProviderDetails(id string, identityProviderID stri identityProviderID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessIdentityProvider{}, err } @@ -130,21 +132,21 @@ func (api *API) accessIdentityProviderDetails(id string, identityProviderID stri // CreateAccessIdentityProvider creates a new Access Identity Provider. // // API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) CreateAccessIdentityProvider(accountID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.createAccessIdentityProvider(accountID, identityProviderConfiguration, AccountRouteRoot) +func (api *API) CreateAccessIdentityProvider(ctx context.Context, accountID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { + return api.createAccessIdentityProvider(ctx, accountID, identityProviderConfiguration, AccountRouteRoot) } // CreateZoneLevelAccessIdentityProvider creates a new zone level Access Identity Provider. // // API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-create-access-identity-provider -func (api *API) CreateZoneLevelAccessIdentityProvider(zoneID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.createAccessIdentityProvider(zoneID, identityProviderConfiguration, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessIdentityProvider(ctx context.Context, zoneID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { + return api.createAccessIdentityProvider(ctx, zoneID, identityProviderConfiguration, ZoneRouteRoot) } -func (api *API) createAccessIdentityProvider(id string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { +func (api *API) createAccessIdentityProvider(ctx context.Context, id string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { uri := fmt.Sprintf("/%s/%s/access/identity_providers", routeRoot, id) - res, err := api.makeRequest("POST", uri, identityProviderConfiguration) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, identityProviderConfiguration) if err != nil { return AccessIdentityProvider{}, err } @@ -162,19 +164,19 @@ func (api *API) createAccessIdentityProvider(id string, identityProviderConfigur // Provider. // // API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) UpdateAccessIdentityProvider(accountID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.updateAccessIdentityProvider(accountID, identityProviderUUID, identityProviderConfiguration, AccountRouteRoot) +func (api *API) UpdateAccessIdentityProvider(ctx context.Context, accountID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { + return api.updateAccessIdentityProvider(ctx, accountID, identityProviderUUID, identityProviderConfiguration, AccountRouteRoot) } // UpdateZoneLevelAccessIdentityProvider updates an existing zone level Access Identity // Provider. // // API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-update-access-identity-provider -func (api *API) UpdateZoneLevelAccessIdentityProvider(zoneID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { - return api.updateAccessIdentityProvider(zoneID, identityProviderUUID, identityProviderConfiguration, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessIdentityProvider(ctx context.Context, zoneID, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider) (AccessIdentityProvider, error) { + return api.updateAccessIdentityProvider(ctx, zoneID, identityProviderUUID, identityProviderConfiguration, ZoneRouteRoot) } -func (api *API) updateAccessIdentityProvider(id string, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { +func (api *API) updateAccessIdentityProvider(ctx context.Context, id string, identityProviderUUID string, identityProviderConfiguration AccessIdentityProvider, routeRoot RouteRoot) (AccessIdentityProvider, error) { uri := fmt.Sprintf( "/%s/%s/access/identity_providers/%s", routeRoot, @@ -182,7 +184,7 @@ func (api *API) updateAccessIdentityProvider(id string, identityProviderUUID str identityProviderUUID, ) - res, err := api.makeRequest("PUT", uri, identityProviderConfiguration) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, identityProviderConfiguration) if err != nil { return AccessIdentityProvider{}, err } @@ -199,18 +201,18 @@ func (api *API) updateAccessIdentityProvider(id string, identityProviderUUID str // DeleteAccessIdentityProvider deletes an Access Identity Provider. // // API reference: https://api.cloudflare.com/#access-identity-providers-create-access-identity-provider -func (api *API) DeleteAccessIdentityProvider(accountID, identityProviderUUID string) (AccessIdentityProvider, error) { - return api.deleteAccessIdentityProvider(accountID, identityProviderUUID, AccountRouteRoot) +func (api *API) DeleteAccessIdentityProvider(ctx context.Context, accountID, identityProviderUUID string) (AccessIdentityProvider, error) { + return api.deleteAccessIdentityProvider(ctx, accountID, identityProviderUUID, AccountRouteRoot) } // DeleteZoneLevelAccessIdentityProvider deletes a zone level Access Identity Provider. // // API reference: https://api.cloudflare.com/#zone-level-access-identity-providers-delete-access-identity-provider -func (api *API) DeleteZoneLevelAccessIdentityProvider(zoneID, identityProviderUUID string) (AccessIdentityProvider, error) { - return api.deleteAccessIdentityProvider(zoneID, identityProviderUUID, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessIdentityProvider(ctx context.Context, zoneID, identityProviderUUID string) (AccessIdentityProvider, error) { + return api.deleteAccessIdentityProvider(ctx, zoneID, identityProviderUUID, ZoneRouteRoot) } -func (api *API) deleteAccessIdentityProvider(id string, identityProviderUUID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { +func (api *API) deleteAccessIdentityProvider(ctx context.Context, id string, identityProviderUUID string, routeRoot RouteRoot) (AccessIdentityProvider, error) { uri := fmt.Sprintf( "/%s/%s/access/identity_providers/%s", routeRoot, @@ -218,7 +220,7 @@ func (api *API) deleteAccessIdentityProvider(id string, identityProviderUUID str identityProviderUUID, ) - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return AccessIdentityProvider{}, err } diff --git a/access_identity_provider_test.go b/access_identity_provider_test.go index e1886575865..484cd063f36 100644 --- a/access_identity_provider_test.go +++ b/access_identity_provider_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -13,7 +14,7 @@ func TestAccessIdentityProviders(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -48,7 +49,7 @@ func TestAccessIdentityProviders(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/identity_providers", handler) - actual, err := client.AccessIdentityProviders(accountID) + actual, err := client.AccessIdentityProviders(context.TODO(), accountID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -56,7 +57,7 @@ func TestAccessIdentityProviders(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/identity_providers", handler) - actual, err = client.ZoneLevelAccessIdentityProviders(zoneID) + actual, err = client.ZoneLevelAccessIdentityProviders(context.TODO(), zoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -68,7 +69,7 @@ func TestAccessIdentityProviderDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -99,7 +100,7 @@ func TestAccessIdentityProviderDetails(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc841", handler) - actual, err := client.AccessIdentityProviderDetails(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc841") + actual, err := client.AccessIdentityProviderDetails(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc841") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -107,7 +108,7 @@ func TestAccessIdentityProviderDetails(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc841", handler) - actual, err = client.ZoneLevelAccessIdentityProviderDetails(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc841") + actual, err = client.ZoneLevelAccessIdentityProviderDetails(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc841") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -119,7 +120,7 @@ func TestCreateAccessIdentityProvider(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -159,7 +160,7 @@ func TestCreateAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/identity_providers", handler) - actual, err := client.CreateAccessIdentityProvider(accountID, newIdentityProvider) + actual, err := client.CreateAccessIdentityProvider(context.TODO(), accountID, newIdentityProvider) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -167,7 +168,7 @@ func TestCreateAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/identity_providers", handler) - actual, err = client.CreateZoneLevelAccessIdentityProvider(zoneID, newIdentityProvider) + actual, err = client.CreateZoneLevelAccessIdentityProvider(context.TODO(), zoneID, newIdentityProvider) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -178,7 +179,7 @@ func TestUpdateAccessIdentityProvider(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -218,7 +219,7 @@ func TestUpdateAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.UpdateAccessIdentityProvider(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", updatedIdentityProvider) + actual, err := client.UpdateAccessIdentityProvider(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", updatedIdentityProvider) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -226,7 +227,7 @@ func TestUpdateAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.UpdateZoneLevelAccessIdentityProvider(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", updatedIdentityProvider) + actual, err = client.UpdateZoneLevelAccessIdentityProvider(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", updatedIdentityProvider) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -238,7 +239,7 @@ func TestDeleteAccessIdentityProvider(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -269,7 +270,7 @@ func TestDeleteAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.DeleteAccessIdentityProvider("01a7362d577a6c3019a474fd6f485823", "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err := client.DeleteAccessIdentityProvider(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -277,7 +278,7 @@ func TestDeleteAccessIdentityProvider(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/identity_providers/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.DeleteZoneLevelAccessIdentityProvider(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err = client.DeleteZoneLevelAccessIdentityProvider(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) diff --git a/access_mutual_tls_certificates.go b/access_mutual_tls_certificates.go index d54e270eb6f..007ddef21e8 100644 --- a/access_mutual_tls_certificates.go +++ b/access_mutual_tls_certificates.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -40,26 +41,26 @@ type AccessMutualTLSCertificateDetailResponse struct { // level. // // API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-properties -func (api *API) AccessMutualTLSCertificates(accountID string) ([]AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificates(accountID, AccountRouteRoot) +func (api *API) AccessMutualTLSCertificates(ctx context.Context, accountID string) ([]AccessMutualTLSCertificate, error) { + return api.accessMutualTLSCertificates(ctx, accountID, AccountRouteRoot) } // ZoneAccessMutualTLSCertificates returns all Access TLS certificates for the // zone level. // // API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-properties -func (api *API) ZoneAccessMutualTLSCertificates(zoneID string) ([]AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificates(zoneID, ZoneRouteRoot) +func (api *API) ZoneAccessMutualTLSCertificates(ctx context.Context, zoneID string) ([]AccessMutualTLSCertificate, error) { + return api.accessMutualTLSCertificates(ctx, zoneID, ZoneRouteRoot) } -func (api *API) accessMutualTLSCertificates(id string, routeRoot RouteRoot) ([]AccessMutualTLSCertificate, error) { +func (api *API) accessMutualTLSCertificates(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessMutualTLSCertificate, error) { uri := fmt.Sprintf( "/%s/%s/access/certificates", routeRoot, id, ) - res, err := api.makeRequestContext(context.Background(), "GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessMutualTLSCertificate{}, err } @@ -77,19 +78,19 @@ func (api *API) accessMutualTLSCertificates(id string, routeRoot RouteRoot) ([]A // certificate. // // API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-access-certificate-details -func (api *API) AccessMutualTLSCertificate(accountID, certificateID string) (AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificate(accountID, certificateID, AccountRouteRoot) +func (api *API) AccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string) (AccessMutualTLSCertificate, error) { + return api.accessMutualTLSCertificate(ctx, accountID, certificateID, AccountRouteRoot) } // ZoneAccessMutualTLSCertificate returns a single zone level Access Mutual TLS // certificate. // // API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-access-certificate-details -func (api *API) ZoneAccessMutualTLSCertificate(zoneID, certificateID string) (AccessMutualTLSCertificate, error) { - return api.accessMutualTLSCertificate(zoneID, certificateID, ZoneRouteRoot) +func (api *API) ZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string) (AccessMutualTLSCertificate, error) { + return api.accessMutualTLSCertificate(ctx, zoneID, certificateID, ZoneRouteRoot) } -func (api *API) accessMutualTLSCertificate(id, certificateID string, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { +func (api *API) accessMutualTLSCertificate(ctx context.Context, id, certificateID string, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { uri := fmt.Sprintf( "/%s/%s/access/certificates/%s", routeRoot, @@ -97,7 +98,7 @@ func (api *API) accessMutualTLSCertificate(id, certificateID string, routeRoot R certificateID, ) - res, err := api.makeRequestContext(context.Background(), "GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessMutualTLSCertificate{}, err } @@ -115,26 +116,26 @@ func (api *API) accessMutualTLSCertificate(id, certificateID string, routeRoot R // certificate. // // API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-create-access-certificate -func (api *API) CreateAccessMutualTLSCertificate(accountID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.createAccessMutualTLSCertificate(accountID, certificate, AccountRouteRoot) +func (api *API) CreateAccessMutualTLSCertificate(ctx context.Context, accountID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { + return api.createAccessMutualTLSCertificate(ctx, accountID, certificate, AccountRouteRoot) } // CreateZoneAccessMutualTLSCertificate creates a zone level Access TLS Mutual // certificate. // // API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-create-access-certificate -func (api *API) CreateZoneAccessMutualTLSCertificate(zoneID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.createAccessMutualTLSCertificate(zoneID, certificate, ZoneRouteRoot) +func (api *API) CreateZoneAccessMutualTLSCertificate(ctx context.Context, zoneID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { + return api.createAccessMutualTLSCertificate(ctx, zoneID, certificate, ZoneRouteRoot) } -func (api *API) createAccessMutualTLSCertificate(id string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { +func (api *API) createAccessMutualTLSCertificate(ctx context.Context, id string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { uri := fmt.Sprintf( "/%s/%s/access/certificates", routeRoot, id, ) - res, err := api.makeRequestContext(context.Background(), "POST", uri, certificate) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, certificate) if err != nil { return AccessMutualTLSCertificate{}, err } @@ -152,19 +153,19 @@ func (api *API) createAccessMutualTLSCertificate(id string, certificate AccessMu // certificate. // // API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-update-access-certificate -func (api *API) UpdateAccessMutualTLSCertificate(accountID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.updateAccessMutualTLSCertificate(accountID, certificateID, certificate, AccountRouteRoot) +func (api *API) UpdateAccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { + return api.updateAccessMutualTLSCertificate(ctx, accountID, certificateID, certificate, AccountRouteRoot) } // UpdateZoneAccessMutualTLSCertificate updates a zone level Access TLS Mutual // certificate. // // API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-update-access-certificate -func (api *API) UpdateZoneAccessMutualTLSCertificate(zoneID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { - return api.updateAccessMutualTLSCertificate(zoneID, certificateID, certificate, ZoneRouteRoot) +func (api *API) UpdateZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string, certificate AccessMutualTLSCertificate) (AccessMutualTLSCertificate, error) { + return api.updateAccessMutualTLSCertificate(ctx, zoneID, certificateID, certificate, ZoneRouteRoot) } -func (api *API) updateAccessMutualTLSCertificate(id string, certificateID string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { +func (api *API) updateAccessMutualTLSCertificate(ctx context.Context, id string, certificateID string, certificate AccessMutualTLSCertificate, routeRoot RouteRoot) (AccessMutualTLSCertificate, error) { uri := fmt.Sprintf( "/%s/%s/access/certificates/%s", routeRoot, @@ -172,7 +173,7 @@ func (api *API) updateAccessMutualTLSCertificate(id string, certificateID string certificateID, ) - res, err := api.makeRequestContext(context.Background(), "PUT", uri, certificate) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, certificate) if err != nil { return AccessMutualTLSCertificate{}, err } @@ -190,19 +191,19 @@ func (api *API) updateAccessMutualTLSCertificate(id string, certificateID string // TLS certificate. // // API reference: https://api.cloudflare.com/#access-mutual-tls-authentication-update-access-certificate -func (api *API) DeleteAccessMutualTLSCertificate(accountID, certificateID string) error { - return api.deleteAccessMutualTLSCertificate(accountID, certificateID, AccountRouteRoot) +func (api *API) DeleteAccessMutualTLSCertificate(ctx context.Context, accountID, certificateID string) error { + return api.deleteAccessMutualTLSCertificate(ctx, accountID, certificateID, AccountRouteRoot) } // DeleteZoneAccessMutualTLSCertificate destroys a zone level Access Mutual TLS // certificate. // // API reference: https://api.cloudflare.com/#zone-level-access-mutual-tls-authentication-update-access-certificate -func (api *API) DeleteZoneAccessMutualTLSCertificate(zoneID, certificateID string) error { - return api.deleteAccessMutualTLSCertificate(zoneID, certificateID, ZoneRouteRoot) +func (api *API) DeleteZoneAccessMutualTLSCertificate(ctx context.Context, zoneID, certificateID string) error { + return api.deleteAccessMutualTLSCertificate(ctx, zoneID, certificateID, ZoneRouteRoot) } -func (api *API) deleteAccessMutualTLSCertificate(id, certificateID string, routeRoot RouteRoot) error { +func (api *API) deleteAccessMutualTLSCertificate(ctx context.Context, id, certificateID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/certificates/%s", routeRoot, @@ -210,7 +211,7 @@ func (api *API) deleteAccessMutualTLSCertificate(id, certificateID string, route certificateID, ) - res, err := api.makeRequestContext(context.Background(), "DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/access_mutual_tls_certificates_test.go b/access_mutual_tls_certificates_test.go index 6b1c1f87d9b..389a233034c 100644 --- a/access_mutual_tls_certificates_test.go +++ b/access_mutual_tls_certificates_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestAccessMutualTLSCertificates(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -52,7 +53,7 @@ func TestAccessMutualTLSCertificates(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/certificates", handler) - actual, err := client.AccessMutualTLSCertificates(accountID) + actual, err := client.AccessMutualTLSCertificates(context.TODO(), accountID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -60,7 +61,7 @@ func TestAccessMutualTLSCertificates(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/certificates", handler) - actual, err = client.ZoneAccessMutualTLSCertificates(zoneID) + actual, err = client.ZoneAccessMutualTLSCertificates(context.TODO(), zoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -72,7 +73,7 @@ func TestAccessMutualTLSCertificate(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -108,7 +109,7 @@ func TestAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.AccessMutualTLSCertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err := client.AccessMutualTLSCertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -116,7 +117,7 @@ func TestAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.ZoneAccessMutualTLSCertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + actual, err = client.ZoneAccessMutualTLSCertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -128,7 +129,7 @@ func TestCreateAccessMutualTLSCertificate(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -169,7 +170,7 @@ func TestCreateAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/certificates", handler) - actual, err := client.CreateAccessMutualTLSCertificate(accountID, certificate) + actual, err := client.CreateAccessMutualTLSCertificate(context.TODO(), accountID, certificate) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -177,7 +178,7 @@ func TestCreateAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/certificates", handler) - actual, err = client.CreateZoneAccessMutualTLSCertificate(zoneID, certificate) + actual, err = client.CreateZoneAccessMutualTLSCertificate(context.TODO(), zoneID, certificate) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -189,7 +190,7 @@ func TestUpdateAccessMutualTLSCertificate(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -230,7 +231,7 @@ func TestUpdateAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.UpdateAccessMutualTLSCertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", certificate) + actual, err := client.UpdateAccessMutualTLSCertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", certificate) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -238,7 +239,7 @@ func TestUpdateAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.UpdateZoneAccessMutualTLSCertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", certificate) + actual, err = client.UpdateZoneAccessMutualTLSCertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", certificate) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -250,7 +251,7 @@ func TestDeleteAccessMutualTLSCertificate(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -264,13 +265,13 @@ func TestDeleteAccessMutualTLSCertificate(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - err := client.DeleteAccessMutualTLSCertificate(accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + err := client.DeleteAccessMutualTLSCertificate(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/certificates/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - err = client.DeleteZoneAccessMutualTLSCertificate(zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") + err = client.DeleteZoneAccessMutualTLSCertificate(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") assert.NoError(t, err) } diff --git a/access_organization.go b/access_organization.go index 1dd6eda4da9..774c3febaff 100644 --- a/access_organization.go +++ b/access_organization.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -44,21 +46,21 @@ type AccessOrganizationDetailResponse struct { // AccessOrganization returns the Access organisation details. // // API reference: https://api.cloudflare.com/#access-organizations-access-organization-details -func (api *API) AccessOrganization(accountID string) (AccessOrganization, ResultInfo, error) { - return api.accessOrganization(accountID, AccountRouteRoot) +func (api *API) AccessOrganization(ctx context.Context, accountID string) (AccessOrganization, ResultInfo, error) { + return api.accessOrganization(ctx, accountID, AccountRouteRoot) } // ZoneLevelAccessOrganization returns the zone level Access organisation details. // // API reference: https://api.cloudflare.com/#zone-level-access-organizations-access-organization-details -func (api *API) ZoneLevelAccessOrganization(zoneID string) (AccessOrganization, ResultInfo, error) { - return api.accessOrganization(zoneID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessOrganization(ctx context.Context, zoneID string) (AccessOrganization, ResultInfo, error) { + return api.accessOrganization(ctx, zoneID, ZoneRouteRoot) } -func (api *API) accessOrganization(id string, routeRoot RouteRoot) (AccessOrganization, ResultInfo, error) { +func (api *API) accessOrganization(ctx context.Context, id string, routeRoot RouteRoot) (AccessOrganization, ResultInfo, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessOrganization{}, ResultInfo{}, err } @@ -75,21 +77,21 @@ func (api *API) accessOrganization(id string, routeRoot RouteRoot) (AccessOrgani // CreateAccessOrganization creates the Access organisation details. // // API reference: https://api.cloudflare.com/#access-organizations-create-access-organization -func (api *API) CreateAccessOrganization(accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.createAccessOrganization(accountID, accessOrganization, AccountRouteRoot) +func (api *API) CreateAccessOrganization(ctx context.Context, accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { + return api.createAccessOrganization(ctx, accountID, accessOrganization, AccountRouteRoot) } // CreateZoneLevelAccessOrganization creates the zone level Access organisation details. // // API reference: https://api.cloudflare.com/#zone-level-access-organizations-create-access-organization -func (api *API) CreateZoneLevelAccessOrganization(zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.createAccessOrganization(zoneID, accessOrganization, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessOrganization(ctx context.Context, zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { + return api.createAccessOrganization(ctx, zoneID, accessOrganization, ZoneRouteRoot) } -func (api *API) createAccessOrganization(id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { +func (api *API) createAccessOrganization(ctx context.Context, id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - res, err := api.makeRequest("POST", uri, accessOrganization) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessOrganization) if err != nil { return AccessOrganization{}, err } @@ -106,21 +108,21 @@ func (api *API) createAccessOrganization(id string, accessOrganization AccessOrg // UpdateAccessOrganization updates the Access organisation details. // // API reference: https://api.cloudflare.com/#access-organizations-update-access-organization -func (api *API) UpdateAccessOrganization(accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.updateAccessOrganization(accountID, accessOrganization, AccountRouteRoot) +func (api *API) UpdateAccessOrganization(ctx context.Context, accountID string, accessOrganization AccessOrganization) (AccessOrganization, error) { + return api.updateAccessOrganization(ctx, accountID, accessOrganization, AccountRouteRoot) } // UpdateZoneLevelAccessOrganization updates the zone level Access organisation details. // // API reference: https://api.cloudflare.com/#zone-level-access-organizations-update-access-organization -func (api *API) UpdateZoneLevelAccessOrganization(zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { - return api.updateAccessOrganization(zoneID, accessOrganization, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessOrganization(ctx context.Context, zoneID string, accessOrganization AccessOrganization) (AccessOrganization, error) { + return api.updateAccessOrganization(ctx, zoneID, accessOrganization, ZoneRouteRoot) } -func (api *API) updateAccessOrganization(id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { +func (api *API) updateAccessOrganization(ctx context.Context, id string, accessOrganization AccessOrganization, routeRoot RouteRoot) (AccessOrganization, error) { uri := fmt.Sprintf("/%s/%s/access/organizations", routeRoot, id) - res, err := api.makeRequest("PUT", uri, accessOrganization) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessOrganization) if err != nil { return AccessOrganization{}, err } diff --git a/access_organization_test.go b/access_organization_test.go index a979ef28993..aa41c6a3c5f 100644 --- a/access_organization_test.go +++ b/access_organization_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestAccessOrganization(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -52,7 +53,7 @@ func TestAccessOrganization(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/organizations", handler) - actual, _, err := client.AccessOrganization(accountID) + actual, _, err := client.AccessOrganization(context.TODO(), accountID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -60,7 +61,7 @@ func TestAccessOrganization(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/organizations", handler) - actual, _, err = client.ZoneLevelAccessOrganization(zoneID) + actual, _, err = client.ZoneLevelAccessOrganization(context.TODO(), zoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -72,7 +73,7 @@ func TestCreateAccessOrganization(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -110,7 +111,7 @@ func TestCreateAccessOrganization(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/organizations", handler) - actual, err := client.CreateAccessOrganization(accountID, want) + actual, err := client.CreateAccessOrganization(context.TODO(), accountID, want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -118,7 +119,7 @@ func TestCreateAccessOrganization(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/organizations", handler) - actual, err = client.CreateZoneLevelAccessOrganization(zoneID, want) + actual, err = client.CreateZoneLevelAccessOrganization(context.TODO(), zoneID, want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -130,7 +131,7 @@ func TestUpdateAccessOrganization(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -168,7 +169,7 @@ func TestUpdateAccessOrganization(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/organizations", handler) - actual, err := client.UpdateAccessOrganization(accountID, want) + actual, err := client.UpdateAccessOrganization(context.TODO(), accountID, want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -176,7 +177,7 @@ func TestUpdateAccessOrganization(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/organizations", handler) - actual, err = client.UpdateZoneLevelAccessOrganization(zoneID, want) + actual, err = client.UpdateZoneLevelAccessOrganization(context.TODO(), zoneID, want) if assert.NoError(t, err) { assert.Equal(t, want, actual) diff --git a/access_policy.go b/access_policy.go index 26f4cf7cf6f..0a9e03892f2 100644 --- a/access_policy.go +++ b/access_policy.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "time" @@ -53,18 +55,18 @@ type AccessPolicyDetailResponse struct { // AccessPolicies returns all access policies for an access application. // // API reference: https://api.cloudflare.com/#access-policy-list-access-policies -func (api *API) AccessPolicies(accountID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { - return api.accessPolicies(accountID, applicationID, pageOpts, AccountRouteRoot) +func (api *API) AccessPolicies(ctx context.Context, accountID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { + return api.accessPolicies(ctx, accountID, applicationID, pageOpts, AccountRouteRoot) } // ZoneLevelAccessPolicies returns all zone level access policies for an access application. // // API reference: https://api.cloudflare.com/#zone-level-access-policy-list-access-policies -func (api *API) ZoneLevelAccessPolicies(zoneID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { - return api.accessPolicies(zoneID, applicationID, pageOpts, ZoneRouteRoot) +func (api *API) ZoneLevelAccessPolicies(ctx context.Context, zoneID, applicationID string, pageOpts PaginationOptions) ([]AccessPolicy, ResultInfo, error) { + return api.accessPolicies(ctx, zoneID, applicationID, pageOpts, ZoneRouteRoot) } -func (api *API) accessPolicies(id string, applicationID string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessPolicy, ResultInfo, error) { +func (api *API) accessPolicies(ctx context.Context, id string, applicationID string, pageOpts PaginationOptions, routeRoot RouteRoot) ([]AccessPolicy, ResultInfo, error) { v := url.Values{} if pageOpts.PerPage > 0 { v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) @@ -84,7 +86,7 @@ func (api *API) accessPolicies(id string, applicationID string, pageOpts Paginat uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessPolicy{}, ResultInfo{}, err } @@ -101,18 +103,18 @@ func (api *API) accessPolicies(id string, applicationID string, pageOpts Paginat // AccessPolicy returns a single policy based on the policy ID. // // API reference: https://api.cloudflare.com/#access-policy-access-policy-details -func (api *API) AccessPolicy(accountID, applicationID, policyID string) (AccessPolicy, error) { - return api.accessPolicy(accountID, applicationID, policyID, AccountRouteRoot) +func (api *API) AccessPolicy(ctx context.Context, accountID, applicationID, policyID string) (AccessPolicy, error) { + return api.accessPolicy(ctx, accountID, applicationID, policyID, AccountRouteRoot) } // ZoneLevelAccessPolicy returns a single zone level policy based on the policy ID. // // API reference: https://api.cloudflare.com/#zone-level-access-policy-access-policy-details -func (api *API) ZoneLevelAccessPolicy(zoneID, applicationID, policyID string) (AccessPolicy, error) { - return api.accessPolicy(zoneID, applicationID, policyID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID, policyID string) (AccessPolicy, error) { + return api.accessPolicy(ctx, zoneID, applicationID, policyID, ZoneRouteRoot) } -func (api *API) accessPolicy(id string, applicationID string, policyID string, routeRoot RouteRoot) (AccessPolicy, error) { +func (api *API) accessPolicy(ctx context.Context, id string, applicationID string, policyID string, routeRoot RouteRoot) (AccessPolicy, error) { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/policies/%s", routeRoot, @@ -121,7 +123,7 @@ func (api *API) accessPolicy(id string, applicationID string, policyID string, r policyID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccessPolicy{}, err } @@ -138,18 +140,18 @@ func (api *API) accessPolicy(id string, applicationID string, policyID string, r // CreateAccessPolicy creates a new access policy. // // API reference: https://api.cloudflare.com/#access-policy-create-access-policy -func (api *API) CreateAccessPolicy(accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.createAccessPolicy(accountID, applicationID, accessPolicy, AccountRouteRoot) +func (api *API) CreateAccessPolicy(ctx context.Context, accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { + return api.createAccessPolicy(ctx, accountID, applicationID, accessPolicy, AccountRouteRoot) } // CreateZoneLevelAccessPolicy creates a new zone level access policy. // // API reference: https://api.cloudflare.com/#zone-level-access-policy-create-access-policy -func (api *API) CreateZoneLevelAccessPolicy(zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.createAccessPolicy(zoneID, applicationID, accessPolicy, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { + return api.createAccessPolicy(ctx, zoneID, applicationID, accessPolicy, ZoneRouteRoot) } -func (api *API) createAccessPolicy(id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { +func (api *API) createAccessPolicy(ctx context.Context, id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/policies", routeRoot, @@ -157,7 +159,7 @@ func (api *API) createAccessPolicy(id, applicationID string, accessPolicy Access applicationID, ) - res, err := api.makeRequest("POST", uri, accessPolicy) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessPolicy) if err != nil { return AccessPolicy{}, err } @@ -174,18 +176,18 @@ func (api *API) createAccessPolicy(id, applicationID string, accessPolicy Access // UpdateAccessPolicy updates an existing access policy. // // API reference: https://api.cloudflare.com/#access-policy-update-access-policy -func (api *API) UpdateAccessPolicy(accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.updateAccessPolicy(accountID, applicationID, accessPolicy, AccountRouteRoot) +func (api *API) UpdateAccessPolicy(ctx context.Context, accountID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { + return api.updateAccessPolicy(ctx, accountID, applicationID, accessPolicy, AccountRouteRoot) } // UpdateZoneLevelAccessPolicy updates an existing zone level access policy. // // API reference: https://api.cloudflare.com/#zone-level-access-policy-update-access-policy -func (api *API) UpdateZoneLevelAccessPolicy(zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { - return api.updateAccessPolicy(zoneID, applicationID, accessPolicy, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID string, accessPolicy AccessPolicy) (AccessPolicy, error) { + return api.updateAccessPolicy(ctx, zoneID, applicationID, accessPolicy, ZoneRouteRoot) } -func (api *API) updateAccessPolicy(id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { +func (api *API) updateAccessPolicy(ctx context.Context, id, applicationID string, accessPolicy AccessPolicy, routeRoot RouteRoot) (AccessPolicy, error) { if accessPolicy.ID == "" { return AccessPolicy{}, errors.Errorf("access policy ID cannot be empty") } @@ -197,7 +199,7 @@ func (api *API) updateAccessPolicy(id, applicationID string, accessPolicy Access accessPolicy.ID, ) - res, err := api.makeRequest("PUT", uri, accessPolicy) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, accessPolicy) if err != nil { return AccessPolicy{}, err } @@ -214,18 +216,18 @@ func (api *API) updateAccessPolicy(id, applicationID string, accessPolicy Access // DeleteAccessPolicy deletes an access policy. // // API reference: https://api.cloudflare.com/#access-policy-update-access-policy -func (api *API) DeleteAccessPolicy(accountID, applicationID, accessPolicyID string) error { - return api.deleteAccessPolicy(accountID, applicationID, accessPolicyID, AccountRouteRoot) +func (api *API) DeleteAccessPolicy(ctx context.Context, accountID, applicationID, accessPolicyID string) error { + return api.deleteAccessPolicy(ctx, accountID, applicationID, accessPolicyID, AccountRouteRoot) } // DeleteZoneLevelAccessPolicy deletes a zone level access policy. // // API reference: https://api.cloudflare.com/#zone-level-access-policy-delete-access-policy -func (api *API) DeleteZoneLevelAccessPolicy(zoneID, applicationID, accessPolicyID string) error { - return api.deleteAccessPolicy(zoneID, applicationID, accessPolicyID, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessPolicy(ctx context.Context, zoneID, applicationID, accessPolicyID string) error { + return api.deleteAccessPolicy(ctx, zoneID, applicationID, accessPolicyID, ZoneRouteRoot) } -func (api *API) deleteAccessPolicy(id, applicationID, accessPolicyID string, routeRoot RouteRoot) error { +func (api *API) deleteAccessPolicy(ctx context.Context, id, applicationID, accessPolicyID string, routeRoot RouteRoot) error { uri := fmt.Sprintf( "/%s/%s/access/apps/%s/policies/%s", routeRoot, @@ -234,7 +236,7 @@ func (api *API) deleteAccessPolicy(id, applicationID, accessPolicyID string, rou accessPolicyID, ) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/access_policy_test.go b/access_policy_test.go index 110d536e0f1..f7cc91e0423 100644 --- a/access_policy_test.go +++ b/access_policy_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -41,7 +42,7 @@ func TestAccessPolicies(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -90,7 +91,7 @@ func TestAccessPolicies(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/"+accessApplicationID+"/policies", handler) - actual, _, err := client.AccessPolicies(accountID, accessApplicationID, pageOptions) + actual, _, err := client.AccessPolicies(context.TODO(), accountID, accessApplicationID, pageOptions) if assert.NoError(t, err) { assert.Equal(t, []AccessPolicy{expectedAccessPolicy}, actual) @@ -98,7 +99,7 @@ func TestAccessPolicies(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/"+accessApplicationID+"/policies", handler) - actual, _, err = client.ZoneLevelAccessPolicies(zoneID, accessApplicationID, pageOptions) + actual, _, err = client.ZoneLevelAccessPolicies(context.TODO(), zoneID, accessApplicationID, pageOptions) if assert.NoError(t, err) { assert.Equal(t, []AccessPolicy{expectedAccessPolicy}, actual) @@ -110,7 +111,7 @@ func TestAccessPolicy(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -151,7 +152,7 @@ func TestAccessPolicy(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - actual, err := client.AccessPolicy(accountID, accessApplicationID, accessPolicyID) + actual, err := client.AccessPolicy(context.TODO(), accountID, accessApplicationID, accessPolicyID) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) @@ -159,7 +160,7 @@ func TestAccessPolicy(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - actual, err = client.ZoneLevelAccessPolicy(zoneID, accessApplicationID, accessPolicyID) + actual, err = client.ZoneLevelAccessPolicy(context.TODO(), zoneID, accessApplicationID, accessPolicyID) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) @@ -171,7 +172,7 @@ func TestCreateAccessPolicy(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -232,11 +233,7 @@ func TestCreateAccessPolicy(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/apps/"+accessApplicationID+"/policies", handler) - actual, err := client.CreateAccessPolicy( - accountID, - accessApplicationID, - accessPolicy, - ) + actual, err := client.CreateAccessPolicy(context.TODO(), accountID, accessApplicationID, accessPolicy) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) @@ -244,11 +241,7 @@ func TestCreateAccessPolicy(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/apps/"+accessApplicationID+"/policies", handler) - actual, err = client.CreateZoneLevelAccessPolicy( - zoneID, - accessApplicationID, - accessPolicy, - ) + actual, err = client.CreateZoneLevelAccessPolicy(context.TODO(), zoneID, accessApplicationID, accessPolicy) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) @@ -260,7 +253,7 @@ func TestUpdateAccessPolicy(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -300,14 +293,14 @@ func TestUpdateAccessPolicy(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - actual, err := client.UpdateAccessPolicy(accountID, accessApplicationID, expectedAccessPolicy) + actual, err := client.UpdateAccessPolicy(context.TODO(), accountID, accessApplicationID, expectedAccessPolicy) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) } mux.HandleFunc("/zones/"+zoneID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - actual, err = client.UpdateZoneLevelAccessPolicy(zoneID, accessApplicationID, expectedAccessPolicy) + actual, err = client.UpdateZoneLevelAccessPolicy(context.TODO(), zoneID, accessApplicationID, expectedAccessPolicy) if assert.NoError(t, err) { assert.Equal(t, expectedAccessPolicy, actual) @@ -318,10 +311,10 @@ func TestUpdateAccessPolicyWithMissingID(t *testing.T) { setup() defer teardown() - _, err := client.UpdateAccessPolicy(accountID, accessApplicationID, AccessPolicy{}) + _, err := client.UpdateAccessPolicy(context.TODO(), accountID, accessApplicationID, AccessPolicy{}) assert.EqualError(t, err, "access policy ID cannot be empty") - _, err = client.UpdateZoneLevelAccessPolicy(zoneID, accessApplicationID, AccessPolicy{}) + _, err = client.UpdateZoneLevelAccessPolicy(context.TODO(), zoneID, accessApplicationID, AccessPolicy{}) assert.EqualError(t, err, "access policy ID cannot be empty") } @@ -330,7 +323,7 @@ func TestDeleteAccessPolicy(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -344,12 +337,12 @@ func TestDeleteAccessPolicy(t *testing.T) { } mux.HandleFunc("/accounts/"+accountID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - err := client.DeleteAccessPolicy(accountID, accessApplicationID, accessPolicyID) + err := client.DeleteAccessPolicy(context.TODO(), accountID, accessApplicationID, accessPolicyID) assert.NoError(t, err) mux.HandleFunc("/zones/"+zoneID+"/access/apps/"+accessApplicationID+"/policies/"+accessPolicyID, handler) - err = client.DeleteZoneLevelAccessPolicy(zoneID, accessApplicationID, accessPolicyID) + err = client.DeleteZoneLevelAccessPolicy(context.TODO(), zoneID, accessApplicationID, accessPolicyID) assert.NoError(t, err) } diff --git a/access_service_tokens.go b/access_service_tokens.go index fcbc4b73f39..30619b71b34 100644 --- a/access_service_tokens.go +++ b/access_service_tokens.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -79,21 +81,21 @@ type AccessServiceTokensUpdateDetailResponse struct { // AccessServiceTokens returns all Access Service Tokens for an account. // // API reference: https://api.cloudflare.com/#access-service-tokens-list-access-service-tokens -func (api *API) AccessServiceTokens(accountID string) ([]AccessServiceToken, ResultInfo, error) { - return api.accessServiceTokens(accountID, AccountRouteRoot) +func (api *API) AccessServiceTokens(ctx context.Context, accountID string) ([]AccessServiceToken, ResultInfo, error) { + return api.accessServiceTokens(ctx, accountID, AccountRouteRoot) } // ZoneLevelAccessServiceTokens returns all Access Service Tokens for a zone. // // API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-list-access-service-tokens -func (api *API) ZoneLevelAccessServiceTokens(zoneID string) ([]AccessServiceToken, ResultInfo, error) { - return api.accessServiceTokens(zoneID, ZoneRouteRoot) +func (api *API) ZoneLevelAccessServiceTokens(ctx context.Context, zoneID string) ([]AccessServiceToken, ResultInfo, error) { + return api.accessServiceTokens(ctx, zoneID, ZoneRouteRoot) } -func (api *API) accessServiceTokens(id string, routeRoot RouteRoot) ([]AccessServiceToken, ResultInfo, error) { +func (api *API) accessServiceTokens(ctx context.Context, id string, routeRoot RouteRoot) ([]AccessServiceToken, ResultInfo, error) { uri := fmt.Sprintf("/%s/%s/access/service_tokens", routeRoot, id) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccessServiceToken{}, ResultInfo{}, err } @@ -110,24 +112,24 @@ func (api *API) accessServiceTokens(id string, routeRoot RouteRoot) ([]AccessSer // CreateAccessServiceToken creates a new Access Service Token for an account. // // API reference: https://api.cloudflare.com/#access-service-tokens-create-access-service-token -func (api *API) CreateAccessServiceToken(accountID, name string) (AccessServiceTokenCreateResponse, error) { - return api.createAccessServiceToken(accountID, name, AccountRouteRoot) +func (api *API) CreateAccessServiceToken(ctx context.Context, accountID, name string) (AccessServiceTokenCreateResponse, error) { + return api.createAccessServiceToken(ctx, accountID, name, AccountRouteRoot) } // CreateZoneLevelAccessServiceToken creates a new Access Service Token for a zone. // // API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-create-access-service-token -func (api *API) CreateZoneLevelAccessServiceToken(zoneID, name string) (AccessServiceTokenCreateResponse, error) { - return api.createAccessServiceToken(zoneID, name, ZoneRouteRoot) +func (api *API) CreateZoneLevelAccessServiceToken(ctx context.Context, zoneID, name string) (AccessServiceTokenCreateResponse, error) { + return api.createAccessServiceToken(ctx, zoneID, name, ZoneRouteRoot) } -func (api *API) createAccessServiceToken(id, name string, routeRoot RouteRoot) (AccessServiceTokenCreateResponse, error) { +func (api *API) createAccessServiceToken(ctx context.Context, id, name string, routeRoot RouteRoot) (AccessServiceTokenCreateResponse, error) { uri := fmt.Sprintf("/%s/%s/access/service_tokens", routeRoot, id) marshalledName, _ := json.Marshal(struct { Name string `json:"name"` }{name}) - res, err := api.makeRequest("POST", uri, marshalledName) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, marshalledName) if err != nil { return AccessServiceTokenCreateResponse{}, err @@ -146,26 +148,26 @@ func (api *API) createAccessServiceToken(id, name string, routeRoot RouteRoot) ( // account. // // API reference: https://api.cloudflare.com/#access-service-tokens-update-access-service-token -func (api *API) UpdateAccessServiceToken(accountID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { - return api.updateAccessServiceToken(accountID, uuid, name, AccountRouteRoot) +func (api *API) UpdateAccessServiceToken(ctx context.Context, accountID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { + return api.updateAccessServiceToken(ctx, accountID, uuid, name, AccountRouteRoot) } // UpdateZoneLevelAccessServiceToken updates an existing Access Service Token for a // zone. // // API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-update-access-service-token -func (api *API) UpdateZoneLevelAccessServiceToken(zoneID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { - return api.updateAccessServiceToken(zoneID, uuid, name, ZoneRouteRoot) +func (api *API) UpdateZoneLevelAccessServiceToken(ctx context.Context, zoneID, uuid, name string) (AccessServiceTokenUpdateResponse, error) { + return api.updateAccessServiceToken(ctx, zoneID, uuid, name, ZoneRouteRoot) } -func (api *API) updateAccessServiceToken(id, uuid, name string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { +func (api *API) updateAccessServiceToken(ctx context.Context, id, uuid, name string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { uri := fmt.Sprintf("/%s/%s/access/service_tokens/%s", routeRoot, id, uuid) marshalledName, _ := json.Marshal(struct { Name string `json:"name"` }{name}) - res, err := api.makeRequest("PUT", uri, marshalledName) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, marshalledName) if err != nil { return AccessServiceTokenUpdateResponse{}, err } @@ -183,22 +185,22 @@ func (api *API) updateAccessServiceToken(id, uuid, name string, routeRoot RouteR // account. // // API reference: https://api.cloudflare.com/#access-service-tokens-delete-access-service-token -func (api *API) DeleteAccessServiceToken(accountID, uuid string) (AccessServiceTokenUpdateResponse, error) { - return api.deleteAccessServiceToken(accountID, uuid, AccountRouteRoot) +func (api *API) DeleteAccessServiceToken(ctx context.Context, accountID, uuid string) (AccessServiceTokenUpdateResponse, error) { + return api.deleteAccessServiceToken(ctx, accountID, uuid, AccountRouteRoot) } // DeleteZoneLevelAccessServiceToken removes an existing Access Service Token for a // zone. // // API reference: https://api.cloudflare.com/#zone-level-access-service-tokens-delete-access-service-token -func (api *API) DeleteZoneLevelAccessServiceToken(zoneID, uuid string) (AccessServiceTokenUpdateResponse, error) { - return api.deleteAccessServiceToken(zoneID, uuid, ZoneRouteRoot) +func (api *API) DeleteZoneLevelAccessServiceToken(ctx context.Context, zoneID, uuid string) (AccessServiceTokenUpdateResponse, error) { + return api.deleteAccessServiceToken(ctx, zoneID, uuid, ZoneRouteRoot) } -func (api *API) deleteAccessServiceToken(id, uuid string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { +func (api *API) deleteAccessServiceToken(ctx context.Context, id, uuid string, routeRoot RouteRoot) (AccessServiceTokenUpdateResponse, error) { uri := fmt.Sprintf("/%s/%s/access/service_tokens/%s", routeRoot, id, uuid) - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return AccessServiceTokenUpdateResponse{}, err } diff --git a/access_service_tokens_test.go b/access_service_tokens_test.go index 3674cfae933..c155c23e6af 100644 --- a/access_service_tokens_test.go +++ b/access_service_tokens_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestAccessServiceTokens(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -48,7 +49,7 @@ func TestAccessServiceTokens(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/service_tokens", handler) - actual, _, err := client.AccessServiceTokens(accountID) + actual, _, err := client.AccessServiceTokens(context.TODO(), accountID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -56,7 +57,7 @@ func TestAccessServiceTokens(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/service_tokens", handler) - actual, _, err = client.ZoneLevelAccessServiceTokens(zoneID) + actual, _, err = client.ZoneLevelAccessServiceTokens(context.TODO(), zoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -68,7 +69,7 @@ func TestCreateAccessServiceToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -97,7 +98,7 @@ func TestCreateAccessServiceToken(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/service_tokens", handler) - actual, err := client.CreateAccessServiceToken(accountID, "CI/CD token") + actual, err := client.CreateAccessServiceToken(context.TODO(), accountID, "CI/CD token") if assert.NoError(t, err) { assert.Equal(t, expected, actual) @@ -105,7 +106,7 @@ func TestCreateAccessServiceToken(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/service_tokens", handler) - actual, err = client.CreateZoneLevelAccessServiceToken(zoneID, "CI/CD token") + actual, err = client.CreateZoneLevelAccessServiceToken(context.TODO(), zoneID, "CI/CD token") if assert.NoError(t, err) { assert.Equal(t, expected, actual) @@ -117,7 +118,7 @@ func TestUpdateAccessServiceToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -144,11 +145,7 @@ func TestUpdateAccessServiceToken(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/service_tokens/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.UpdateAccessServiceToken( - accountID, - "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", - "CI/CD token", - ) + actual, err := client.UpdateAccessServiceToken(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", "CI/CD token") if assert.NoError(t, err) { assert.Equal(t, expected, actual) @@ -156,11 +153,7 @@ func TestUpdateAccessServiceToken(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/service_tokens/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.UpdateZoneLevelAccessServiceToken( - zoneID, - "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", - "CI/CD token", - ) + actual, err = client.UpdateZoneLevelAccessServiceToken(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", "CI/CD token") if assert.NoError(t, err) { assert.Equal(t, expected, actual) @@ -172,7 +165,7 @@ func TestDeleteAccessServiceToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -199,10 +192,7 @@ func TestDeleteAccessServiceToken(t *testing.T) { mux.HandleFunc("/accounts/"+accountID+"/access/service_tokens/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err := client.DeleteAccessServiceToken( - accountID, - "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", - ) + actual, err := client.DeleteAccessServiceToken(context.TODO(), accountID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, expected, actual) @@ -210,10 +200,7 @@ func TestDeleteAccessServiceToken(t *testing.T) { mux.HandleFunc("/zones/"+zoneID+"/access/service_tokens/f174e90a-fafe-4643-bbbc-4a0ed4fc8415", handler) - actual, err = client.DeleteZoneLevelAccessServiceToken( - zoneID, - "f174e90a-fafe-4643-bbbc-4a0ed4fc8415", - ) + actual, err = client.DeleteZoneLevelAccessServiceToken(context.TODO(), zoneID, "f174e90a-fafe-4643-bbbc-4a0ed4fc8415") if assert.NoError(t, err) { assert.Equal(t, expected, actual) diff --git a/account_members.go b/account_members.go index adfd95c3ad4..a7ba631693e 100644 --- a/account_members.go +++ b/account_members.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" @@ -55,7 +57,7 @@ type AccountMemberInvitation struct { // AccountMembers returns all members of an account. // // API reference: https://api.cloudflare.com/#accounts-list-accounts -func (api *API) AccountMembers(accountID string, pageOpts PaginationOptions) ([]AccountMember, ResultInfo, error) { +func (api *API) AccountMembers(ctx context.Context, accountID string, pageOpts PaginationOptions) ([]AccountMember, ResultInfo, error) { if accountID == "" { return []AccountMember{}, ResultInfo{}, errors.New(errMissingAccountID) } @@ -73,7 +75,7 @@ func (api *API) AccountMembers(accountID string, pageOpts PaginationOptions) ([] uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccountMember{}, ResultInfo{}, err } @@ -90,7 +92,7 @@ func (api *API) AccountMembers(accountID string, pageOpts PaginationOptions) ([] // CreateAccountMember invites a new member to join an account. // // API reference: https://api.cloudflare.com/#account-members-add-member -func (api *API) CreateAccountMember(accountID string, emailAddress string, roles []string) (AccountMember, error) { +func (api *API) CreateAccountMember(ctx context.Context, accountID string, emailAddress string, roles []string) (AccountMember, error) { if accountID == "" { return AccountMember{}, errors.New(errMissingAccountID) } @@ -101,7 +103,7 @@ func (api *API) CreateAccountMember(accountID string, emailAddress string, roles Email: emailAddress, Roles: roles, } - res, err := api.makeRequest("POST", uri, newMember) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, newMember) if err != nil { return AccountMember{}, err } @@ -118,14 +120,14 @@ func (api *API) CreateAccountMember(accountID string, emailAddress string, roles // DeleteAccountMember removes a member from an account. // // API reference: https://api.cloudflare.com/#account-members-remove-member -func (api *API) DeleteAccountMember(accountID string, userID string) error { +func (api *API) DeleteAccountMember(ctx context.Context, accountID string, userID string) error { if accountID == "" { return errors.New(errMissingAccountID) } uri := fmt.Sprintf("/accounts/%s/members/%s", accountID, userID) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -136,14 +138,14 @@ func (api *API) DeleteAccountMember(accountID string, userID string) error { // UpdateAccountMember modifies an existing account member. // // API reference: https://api.cloudflare.com/#account-members-update-member -func (api *API) UpdateAccountMember(accountID string, userID string, member AccountMember) (AccountMember, error) { +func (api *API) UpdateAccountMember(ctx context.Context, accountID string, userID string, member AccountMember) (AccountMember, error) { if accountID == "" { return AccountMember{}, errors.New(errMissingAccountID) } uri := fmt.Sprintf("/accounts/%s/members/%s", accountID, userID) - res, err := api.makeRequest("PUT", uri, member) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, member) if err != nil { return AccountMember{}, err } @@ -160,7 +162,7 @@ func (api *API) UpdateAccountMember(accountID string, userID string, member Acco // AccountMember returns details of a single account member. // // API reference: https://api.cloudflare.com/#account-members-member-details -func (api *API) AccountMember(accountID string, memberID string) (AccountMember, error) { +func (api *API) AccountMember(ctx context.Context, accountID string, memberID string) (AccountMember, error) { if accountID == "" { return AccountMember{}, errors.New(errMissingAccountID) } @@ -171,7 +173,7 @@ func (api *API) AccountMember(accountID string, memberID string) (AccountMember, memberID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccountMember{}, err } diff --git a/account_members_test.go b/account_members_test.go index 22796677bf6..39a67fe33ee 100644 --- a/account_members_test.go +++ b/account_members_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -82,7 +83,7 @@ func TestAccountMembers(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -132,7 +133,7 @@ func TestAccountMembers(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/members", handler) want := []AccountMember{expectedAccountMemberStruct} - actual, _, err := client.AccountMembers("01a7362d577a6c3019a474fd6f485823", PaginationOptions{}) + actual, _, err := client.AccountMembers(context.TODO(), "01a7362d577a6c3019a474fd6f485823", PaginationOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -143,7 +144,7 @@ func TestAccountMembersWithoutAccountID(t *testing.T) { setup() defer teardown() - _, _, err := client.AccountMembers("", PaginationOptions{}) + _, _, err := client.AccountMembers(context.TODO(), "", PaginationOptions{}) if assert.Error(t, err) { assert.Equal(t, err.Error(), errMissingAccountID) @@ -155,7 +156,7 @@ func TestCreateAccountMember(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -194,10 +195,7 @@ func TestCreateAccountMember(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/members", handler) - actual, err := client.CreateAccountMember( - "01a7362d577a6c3019a474fd6f485823", - "user@example.com", - []string{"3536bcfad5faccb999b47003c79917fb"}) + actual, err := client.CreateAccountMember(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "user@example.com", []string{"3536bcfad5faccb999b47003c79917fb"}) if assert.NoError(t, err) { assert.Equal(t, expectedNewAccountMemberStruct, actual) @@ -208,10 +206,7 @@ func TestCreateAccountMemberWithoutAccountID(t *testing.T) { setup() defer teardown() - _, err := client.CreateAccountMember( - "", - "user@example.com", - []string{"3536bcfad5faccb999b47003c79917fb"}) + _, err := client.CreateAccountMember(context.TODO(), "", "user@example.com", []string{"3536bcfad5faccb999b47003c79917fb"}) if assert.Error(t, err) { assert.Equal(t, err.Error(), errMissingAccountID) @@ -223,7 +218,7 @@ func TestUpdateAccountMember(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -268,11 +263,7 @@ func TestUpdateAccountMember(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/members/4536bcfad5faccb111b47003c79917fa", handler) - actual, err := client.UpdateAccountMember( - "01a7362d577a6c3019a474fd6f485823", - "4536bcfad5faccb111b47003c79917fa", - newUpdatedAccountMemberStruct, - ) + actual, err := client.UpdateAccountMember(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "4536bcfad5faccb111b47003c79917fa", newUpdatedAccountMemberStruct) if assert.NoError(t, err) { assert.Equal(t, newUpdatedAccountMemberStruct, actual) @@ -283,11 +274,7 @@ func TestUpdateAccountMemberWithoutAccountID(t *testing.T) { setup() defer teardown() - _, err := client.UpdateAccountMember( - "", - "4536bcfad5faccb111b47003c79917fa", - newUpdatedAccountMemberStruct, - ) + _, err := client.UpdateAccountMember(context.TODO(), "", "4536bcfad5faccb111b47003c79917fa", newUpdatedAccountMemberStruct) if assert.Error(t, err) { assert.Equal(t, err.Error(), errMissingAccountID) @@ -299,7 +286,7 @@ func TestAccountMember(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -340,7 +327,7 @@ func TestAccountMember(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/members/4536bcfad5faccb111b47003c79917fa", handler) - actual, err := client.AccountMember("01a7362d577a6c3019a474fd6f485823", "4536bcfad5faccb111b47003c79917fa") + actual, err := client.AccountMember(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "4536bcfad5faccb111b47003c79917fa") if assert.NoError(t, err) { assert.Equal(t, expectedAccountMemberStruct, actual) @@ -351,7 +338,7 @@ func TestAccountMemberWithoutAccountID(t *testing.T) { setup() defer teardown() - _, err := client.AccountMember("", "4536bcfad5faccb111b47003c79917fa") + _, err := client.AccountMember(context.TODO(), "", "4536bcfad5faccb111b47003c79917fa") if assert.Error(t, err) { assert.Equal(t, err.Error(), errMissingAccountID) diff --git a/account_roles.go b/account_roles.go index 2f662acf8f5..f884f56ba1c 100644 --- a/account_roles.go +++ b/account_roles.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "github.com/pkg/errors" ) @@ -42,10 +44,10 @@ type AccountRoleDetailResponse struct { // AccountRoles returns all roles of an account. // // API reference: https://api.cloudflare.com/#account-roles-list-roles -func (api *API) AccountRoles(accountID string) ([]AccountRole, error) { +func (api *API) AccountRoles(ctx context.Context, accountID string) ([]AccountRole, error) { uri := "/accounts/" + accountID + "/roles" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []AccountRole{}, err } @@ -62,10 +64,10 @@ func (api *API) AccountRoles(accountID string) ([]AccountRole, error) { // AccountRole returns the details of a single account role. // // API reference: https://api.cloudflare.com/#account-roles-role-details -func (api *API) AccountRole(accountID string, roleID string) (AccountRole, error) { +func (api *API) AccountRole(ctx context.Context, accountID string, roleID string) (AccountRole, error) { uri := fmt.Sprintf("/accounts/%s/roles/%s", accountID, roleID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AccountRole{}, err } diff --git a/account_roles_test.go b/account_roles_test.go index 29060b4bda1..ece4d362913 100644 --- a/account_roles_test.go +++ b/account_roles_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -23,7 +24,7 @@ func TestAccountRoles(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -59,7 +60,7 @@ func TestAccountRoles(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/roles", handler) want := []AccountRole{expectedAccountRole} - actual, err := client.AccountRoles("01a7362d577a6c3019a474fd6f485823") + actual, err := client.AccountRoles(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -71,7 +72,7 @@ func TestAccountRole(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -104,7 +105,7 @@ func TestAccountRole(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/roles/3536bcfad5faccb999b47003c79917fb", handler) - actual, err := client.AccountRole("01a7362d577a6c3019a474fd6f485823", "3536bcfad5faccb999b47003c79917fb") + actual, err := client.AccountRole(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "3536bcfad5faccb999b47003c79917fb") if assert.NoError(t, err) { assert.Equal(t, expectedAccountRole, actual) diff --git a/accounts.go b/accounts.go index 8e4cd5922ed..88ad5d0f437 100644 --- a/accounts.go +++ b/accounts.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" @@ -49,7 +50,7 @@ type AccountDetailResponse struct { // Accounts returns all accounts the logged in user has access to. // // API reference: https://api.cloudflare.com/#accounts-list-accounts -func (api *API) Accounts(pageOpts PaginationOptions) ([]Account, ResultInfo, error) { +func (api *API) Accounts(ctx context.Context, pageOpts PaginationOptions) ([]Account, ResultInfo, error) { v := url.Values{} if pageOpts.PerPage > 0 { v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) @@ -63,7 +64,7 @@ func (api *API) Accounts(pageOpts PaginationOptions) ([]Account, ResultInfo, err uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []Account{}, ResultInfo{}, err } @@ -79,10 +80,10 @@ func (api *API) Accounts(pageOpts PaginationOptions) ([]Account, ResultInfo, err // Account returns a single account based on the ID. // // API reference: https://api.cloudflare.com/#accounts-account-details -func (api *API) Account(accountID string) (Account, ResultInfo, error) { +func (api *API) Account(ctx context.Context, accountID string) (Account, ResultInfo, error) { uri := "/accounts/" + accountID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return Account{}, ResultInfo{}, err } @@ -99,10 +100,10 @@ func (api *API) Account(accountID string) (Account, ResultInfo, error) { // UpdateAccount allows management of an account using the account ID. // // API reference: https://api.cloudflare.com/#accounts-update-account -func (api *API) UpdateAccount(accountID string, account Account) (Account, error) { +func (api *API) UpdateAccount(ctx context.Context, accountID string, account Account) (Account, error) { uri := "/accounts/" + accountID - res, err := api.makeRequest("PUT", uri, account) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, account) if err != nil { return Account{}, err } @@ -123,7 +124,7 @@ func (api *API) UpdateAccount(accountID string, account Account) (Account, error func (api *API) CreateAccount(ctx context.Context, account Account) (Account, error) { uri := "/accounts" - res, err := api.makeRequestContext(ctx, "POST", uri, account) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, account) if err != nil { return Account{}, err } @@ -148,7 +149,7 @@ func (api *API) DeleteAccount(ctx context.Context, accountID string) error { uri := fmt.Sprintf("/accounts/%s", accountID) - _, err := api.makeRequestContext(ctx, "DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/accounts_test.go b/accounts_test.go index 3fcdfc04aec..464ec5b88c9 100644 --- a/accounts_test.go +++ b/accounts_test.go @@ -23,7 +23,7 @@ func TestAccounts(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -51,7 +51,7 @@ func TestAccounts(t *testing.T) { mux.HandleFunc("/accounts", handler) want := []Account{expectedAccountStruct} - actual, _, err := client.Accounts(PaginationOptions{}) + actual, _, err := client.Accounts(context.TODO(), PaginationOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -63,7 +63,7 @@ func TestAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -89,7 +89,7 @@ func TestAccount(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823", handler) want := expectedAccountStruct - actual, _, err := client.Account("01a7362d577a6c3019a474fd6f485823") + actual, _, err := client.Account(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -101,7 +101,7 @@ func TestUpdateAccount(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -146,7 +146,7 @@ func TestUpdateAccount(t *testing.T) { }, } - account, err := client.UpdateAccount(newAccountDetails.ID, newAccountDetails) + account, err := client.UpdateAccount(context.TODO(), newAccountDetails.ID, newAccountDetails) if assert.NoError(t, err) { assert.NotEqual(t, oldAccountDetails.Name, account.Name) assert.Equal(t, account.Name, "Cloudflare Demo - New") @@ -158,7 +158,7 @@ func TestCreateAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -196,7 +196,7 @@ func TestDeleteAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, diff --git a/api_token.go b/api_token.go index 9497c100303..b278675038a 100644 --- a/api_token.go +++ b/api_token.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -92,10 +94,10 @@ type APITokenVerifyBody struct { // GetAPIToken returns a single API token based on the ID. // // API reference: https://api.cloudflare.com/#user-api-tokens-token-details -func (api *API) GetAPIToken(tokenID string) (APIToken, error) { +func (api *API) GetAPIToken(ctx context.Context, tokenID string) (APIToken, error) { uri := "/user/tokens/" + tokenID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return APIToken{}, err } @@ -112,8 +114,8 @@ func (api *API) GetAPIToken(tokenID string) (APIToken, error) { // APITokens returns all available API tokens. // // API reference: https://api.cloudflare.com/#user-api-tokens-list-tokens -func (api *API) APITokens() ([]APIToken, error) { - res, err := api.makeRequest("GET", "/user/tokens", nil) +func (api *API) APITokens(ctx context.Context) ([]APIToken, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens", nil) if err != nil { return []APIToken{}, err } @@ -135,8 +137,8 @@ func (api *API) APITokens() ([]APIToken, error) { // need to roll the token in order to get a new value. // // API reference: https://api.cloudflare.com/#user-api-tokens-create-token -func (api *API) CreateAPIToken(token APIToken) (APIToken, error) { - res, err := api.makeRequest("POST", "/user/tokens", token) +func (api *API) CreateAPIToken(ctx context.Context, token APIToken) (APIToken, error) { + res, err := api.makeRequestContext(ctx, http.MethodPost, "/user/tokens", token) if err != nil { return APIToken{}, err } @@ -153,8 +155,8 @@ func (api *API) CreateAPIToken(token APIToken) (APIToken, error) { // UpdateAPIToken updates an existing API token. // // API reference: https://api.cloudflare.com/#user-api-tokens-update-token -func (api *API) UpdateAPIToken(tokenID string, token APIToken) (APIToken, error) { - res, err := api.makeRequest("PUT", "/user/tokens/"+tokenID, token) +func (api *API) UpdateAPIToken(ctx context.Context, tokenID string, token APIToken) (APIToken, error) { + res, err := api.makeRequestContext(ctx, http.MethodPut, "/user/tokens/"+tokenID, token) if err != nil { return APIToken{}, err } @@ -171,10 +173,10 @@ func (api *API) UpdateAPIToken(tokenID string, token APIToken) (APIToken, error) // RollAPIToken rolls the credential associated with the token. // // API reference: https://api.cloudflare.com/#user-api-tokens-roll-token -func (api *API) RollAPIToken(tokenID string) (string, error) { +func (api *API) RollAPIToken(ctx context.Context, tokenID string) (string, error) { uri := fmt.Sprintf("/user/tokens/%s/value", tokenID) - res, err := api.makeRequest("PUT", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, nil) if err != nil { return "", err } @@ -191,8 +193,8 @@ func (api *API) RollAPIToken(tokenID string) (string, error) { // VerifyAPIToken rolls the value associated with the token. // // API reference: https://api.cloudflare.com/#user-api-tokens-roll-token -func (api *API) VerifyAPIToken() (APITokenVerifyBody, error) { - res, err := api.makeRequest("GET", "/user/tokens/verify", nil) +func (api *API) VerifyAPIToken(ctx context.Context) (APITokenVerifyBody, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens/verify", nil) if err != nil { return APITokenVerifyBody{}, err } @@ -209,8 +211,8 @@ func (api *API) VerifyAPIToken() (APITokenVerifyBody, error) { // DeleteAPIToken deletes a single API token. // // API reference: https://api.cloudflare.com/#user-api-tokens-delete-token -func (api *API) DeleteAPIToken(tokenID string) error { - _, err := api.makeRequest("DELETE", "/user/tokens/"+tokenID, nil) +func (api *API) DeleteAPIToken(ctx context.Context, tokenID string) error { + _, err := api.makeRequestContext(ctx, http.MethodDelete, "/user/tokens/"+tokenID, nil) if err != nil { return err } @@ -221,9 +223,9 @@ func (api *API) DeleteAPIToken(tokenID string) error { // ListAPITokensPermissionGroups returns all available API token permission groups. // // API reference: https://api.cloudflare.com/#permission-groups-list-permission-groups -func (api *API) ListAPITokensPermissionGroups() ([]APITokenPermissionGroups, error) { +func (api *API) ListAPITokensPermissionGroups(ctx context.Context) ([]APITokenPermissionGroups, error) { var r APITokenPermissionGroupsResponse - res, err := api.makeRequest("GET", "/user/tokens/permission_groups", nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/tokens/permission_groups", nil) if err != nil { return []APITokenPermissionGroups{}, err } diff --git a/api_token_test.go b/api_token_test.go index e61701719ae..497583c3e7e 100644 --- a/api_token_test.go +++ b/api_token_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -19,7 +20,7 @@ func TestAPITokens(t *testing.T) { expiresOn, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00Z") handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -108,7 +109,7 @@ func TestAPITokens(t *testing.T) { }, } - actual, err := client.APITokens() + actual, err := client.APITokens(context.TODO()) if assert.NoError(t, err) { assert.Equal(t, []APIToken{expectedAPIToken}, actual) @@ -125,7 +126,7 @@ func TestGetAPIToken(t *testing.T) { expiresOn, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00Z") handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -212,7 +213,7 @@ func TestGetAPIToken(t *testing.T) { }, } - actual, err := client.GetAPIToken("ed17574386854bf78a67040be0a770b0") + actual, err := client.GetAPIToken(context.TODO(), "ed17574386854bf78a67040be0a770b0") if assert.NoError(t, err) { assert.Equal(t, expectedAPIToken, actual) @@ -229,7 +230,7 @@ func TestCreateAPIToken(t *testing.T) { expiresOn, _ := time.Parse(time.RFC3339, "2020-01-01T00:00:00Z") handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success":true, @@ -294,7 +295,7 @@ func TestCreateAPIToken(t *testing.T) { }}, } - actual, err := client.CreateAPIToken(tokenToCreate) + actual, err := client.CreateAPIToken(context.TODO(), tokenToCreate) if assert.NoError(t, err) { assert.Equal(t, tokenToCreate.Name, actual.Name) @@ -307,7 +308,7 @@ func TestRollAPIToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -320,7 +321,7 @@ func TestRollAPIToken(t *testing.T) { mux.HandleFunc("/user/tokens/ed17574386854bf78a67040be0a770b0/value", handler) - actual, err := client.RollAPIToken("ed17574386854bf78a67040be0a770b0") + actual, err := client.RollAPIToken(context.TODO(), "ed17574386854bf78a67040be0a770b0") if assert.NoError(t, err) { assert.Equal(t, "8M7wS6hCpXVc-DoRnPPY_UCWPgy8aea4Wy6kCe5T", actual) @@ -332,7 +333,7 @@ func TestVerifyAPIToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -349,7 +350,7 @@ func TestVerifyAPIToken(t *testing.T) { mux.HandleFunc("/user/tokens/verify", handler) - actual, err := client.VerifyAPIToken() + actual, err := client.VerifyAPIToken(context.TODO()) if assert.NoError(t, err) { assert.Equal(t, "active", actual.Status) @@ -361,7 +362,7 @@ func TestDeleteAPIToken(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -375,7 +376,7 @@ func TestDeleteAPIToken(t *testing.T) { mux.HandleFunc("/user/tokens/ed17574386854bf78a67040be0a770b0", handler) - err := client.DeleteAPIToken("ed17574386854bf78a67040be0a770b0") + err := client.DeleteAPIToken(context.TODO(), "ed17574386854bf78a67040be0a770b0") assert.NoError(t, err) } @@ -386,7 +387,7 @@ func TestListAPITokensPermissionGroups(t *testing.T) { var pgID = "47aa30b6eb97ecae0518b750d6b142b6" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -409,7 +410,7 @@ func TestListAPITokensPermissionGroups(t *testing.T) { Name: "DNS Read", Scopes: []string{"com.cloudflare.api.account.zone"}, }} - actual, err := client.ListAPITokensPermissionGroups() + actual, err := client.ListAPITokensPermissionGroups(context.TODO()) if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/argo.go b/argo.go index 7495d9476a0..e120aed8f15 100644 --- a/argo.go +++ b/argo.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -29,10 +31,10 @@ type ArgoDetailsResponse struct { // ArgoSmartRouting returns the current settings for smart routing. // // API reference: https://api.cloudflare.com/#argo-smart-routing-get-argo-smart-routing-setting -func (api *API) ArgoSmartRouting(zoneID string) (ArgoFeatureSetting, error) { +func (api *API) ArgoSmartRouting(ctx context.Context, zoneID string) (ArgoFeatureSetting, error) { uri := "/zones/" + zoneID + "/argo/smart_routing" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ArgoFeatureSetting{}, err } @@ -48,14 +50,14 @@ func (api *API) ArgoSmartRouting(zoneID string) (ArgoFeatureSetting, error) { // UpdateArgoSmartRouting updates the setting for smart routing. // // API reference: https://api.cloudflare.com/#argo-smart-routing-patch-argo-smart-routing-setting -func (api *API) UpdateArgoSmartRouting(zoneID, settingValue string) (ArgoFeatureSetting, error) { +func (api *API) UpdateArgoSmartRouting(ctx context.Context, zoneID, settingValue string) (ArgoFeatureSetting, error) { if !contains(validSettingValues, settingValue) { return ArgoFeatureSetting{}, errors.New(fmt.Sprintf("invalid setting value '%s'. must be 'on' or 'off'", settingValue)) } uri := "/zones/" + zoneID + "/argo/smart_routing" - res, err := api.makeRequest("PATCH", uri, ArgoFeatureSetting{Value: settingValue}) + res, err := api.makeRequestContext(ctx, "PATCH", uri, ArgoFeatureSetting{Value: settingValue}) if err != nil { return ArgoFeatureSetting{}, err } @@ -71,10 +73,10 @@ func (api *API) UpdateArgoSmartRouting(zoneID, settingValue string) (ArgoFeature // ArgoTieredCaching returns the current settings for tiered caching. // // API reference: TBA -func (api *API) ArgoTieredCaching(zoneID string) (ArgoFeatureSetting, error) { +func (api *API) ArgoTieredCaching(ctx context.Context, zoneID string) (ArgoFeatureSetting, error) { uri := "/zones/" + zoneID + "/argo/tiered_caching" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ArgoFeatureSetting{}, err } @@ -90,14 +92,14 @@ func (api *API) ArgoTieredCaching(zoneID string) (ArgoFeatureSetting, error) { // UpdateArgoTieredCaching updates the setting for tiered caching. // // API reference: TBA -func (api *API) UpdateArgoTieredCaching(zoneID, settingValue string) (ArgoFeatureSetting, error) { +func (api *API) UpdateArgoTieredCaching(ctx context.Context, zoneID, settingValue string) (ArgoFeatureSetting, error) { if !contains(validSettingValues, settingValue) { return ArgoFeatureSetting{}, errors.New(fmt.Sprintf("invalid setting value '%s'. must be 'on' or 'off'", settingValue)) } uri := "/zones/" + zoneID + "/argo/tiered_caching" - res, err := api.makeRequest("PATCH", uri, ArgoFeatureSetting{Value: settingValue}) + res, err := api.makeRequestContext(ctx, "PATCH", uri, ArgoFeatureSetting{Value: settingValue}) if err != nil { return ArgoFeatureSetting{}, err } diff --git a/argo_example_test.go b/argo_example_test.go index 0367628c31b..6e87bb21a74 100644 --- a/argo_example_test.go +++ b/argo_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -13,7 +14,7 @@ func ExampleAPI_ArgoSmartRouting() { log.Fatal(err) } - smartRoutingSettings, err := api.ArgoSmartRouting("01a7362d577a6c3019a474fd6f485823") + smartRoutingSettings, err := api.ArgoSmartRouting(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if err != nil { log.Fatal(err) } @@ -27,7 +28,7 @@ func ExampleAPI_ArgoTieredCaching() { log.Fatal(err) } - tieredCachingSettings, err := api.ArgoTieredCaching("01a7362d577a6c3019a474fd6f485823") + tieredCachingSettings, err := api.ArgoTieredCaching(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if err != nil { log.Fatal(err) } @@ -41,7 +42,7 @@ func ExampleAPI_UpdateArgoSmartRouting() { log.Fatal(err) } - smartRoutingSettings, err := api.UpdateArgoSmartRouting("01a7362d577a6c3019a474fd6f485823", "on") + smartRoutingSettings, err := api.UpdateArgoSmartRouting(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "on") if err != nil { log.Fatal(err) } @@ -55,7 +56,7 @@ func ExampleAPI_UpdateArgoTieredCaching() { log.Fatal(err) } - tieredCachingSettings, err := api.UpdateArgoTieredCaching("01a7362d577a6c3019a474fd6f485823", "on") + tieredCachingSettings, err := api.UpdateArgoTieredCaching(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "on") if err != nil { log.Fatal(err) } diff --git a/argo_test.go b/argo_test.go index 7cd59b0a7d0..36fa0c4914b 100644 --- a/argo_test.go +++ b/argo_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -16,7 +17,7 @@ func TestArgoSmartRouting(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -40,7 +41,7 @@ func TestArgoSmartRouting(t *testing.T) { ModifiedOn: argoTimestamp, } - actual, err := client.ArgoSmartRouting("01a7362d577a6c3019a474fd6f485823") + actual, err := client.ArgoSmartRouting(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -76,7 +77,7 @@ func TestUpdateArgoSmartRouting(t *testing.T) { ModifiedOn: argoTimestamp, } - actual, err := client.UpdateArgoSmartRouting("01a7362d577a6c3019a474fd6f485823", "off") + actual, err := client.UpdateArgoSmartRouting(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "off") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -87,7 +88,7 @@ func TestUpdateArgoSmartRoutingWithInvalidValue(t *testing.T) { setup() defer teardown() - _, err := client.UpdateArgoSmartRouting("01a7362d577a6c3019a474fd6f485823", "notreal") + _, err := client.UpdateArgoSmartRouting(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "notreal") if assert.Error(t, err) { assert.Equal(t, "invalid setting value 'notreal'. must be 'on' or 'off'", err.Error()) @@ -99,7 +100,7 @@ func TestArgoTieredCaching(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -123,7 +124,7 @@ func TestArgoTieredCaching(t *testing.T) { ModifiedOn: argoTimestamp, } - actual, err := client.ArgoTieredCaching("01a7362d577a6c3019a474fd6f485823") + actual, err := client.ArgoTieredCaching(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -159,7 +160,7 @@ func TestUpdateArgoTieredCaching(t *testing.T) { ModifiedOn: argoTimestamp, } - actual, err := client.UpdateArgoTieredCaching("01a7362d577a6c3019a474fd6f485823", "off") + actual, err := client.UpdateArgoTieredCaching(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "off") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -170,7 +171,7 @@ func TestUpdateArgoTieredCachingWithInvalidValue(t *testing.T) { setup() defer teardown() - _, err := client.UpdateArgoTieredCaching("01a7362d577a6c3019a474fd6f485823", "notreal") + _, err := client.UpdateArgoTieredCaching(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "notreal") if assert.Error(t, err) { assert.Equal(t, "invalid setting value 'notreal'. must be 'on' or 'off'", err.Error()) diff --git a/argo_tunnel.go b/argo_tunnel.go index 17d01752cbf..b50b15f7b59 100644 --- a/argo_tunnel.go +++ b/argo_tunnel.go @@ -47,7 +47,7 @@ type ArgoTunnelDetailResponse struct { func (api *API) ArgoTunnels(ctx context.Context, accountID string) ([]ArgoTunnel, error) { uri := "/accounts/" + accountID + "/tunnels" - res, err := api.makeRequestContextWithHeaders(ctx, "GET", uri, nil, argoV1Header()) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodGet, uri, nil, argoV1Header()) if err != nil { return []ArgoTunnel{}, err } @@ -66,7 +66,7 @@ func (api *API) ArgoTunnels(ctx context.Context, accountID string) ([]ArgoTunnel func (api *API) ArgoTunnel(ctx context.Context, accountID, tunnelUUID string) (ArgoTunnel, error) { uri := fmt.Sprintf("/accounts/%s/tunnels/%s", accountID, tunnelUUID) - res, err := api.makeRequestContextWithHeaders(ctx, "GET", uri, nil, argoV1Header()) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodGet, uri, nil, argoV1Header()) if err != nil { return ArgoTunnel{}, err } @@ -87,7 +87,7 @@ func (api *API) CreateArgoTunnel(ctx context.Context, accountID, name, secret st tunnel := ArgoTunnel{Name: name, Secret: secret} - res, err := api.makeRequestContextWithHeaders(ctx, "POST", uri, tunnel, argoV1Header()) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPost, uri, tunnel, argoV1Header()) if err != nil { return ArgoTunnel{}, err } @@ -107,7 +107,7 @@ func (api *API) CreateArgoTunnel(ctx context.Context, accountID, name, secret st func (api *API) DeleteArgoTunnel(ctx context.Context, accountID, tunnelUUID string) error { uri := fmt.Sprintf("/accounts/%s/tunnels/%s", accountID, tunnelUUID) - res, err := api.makeRequestContextWithHeaders(ctx, "DELETE", uri, nil, argoV1Header()) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodDelete, uri, nil, argoV1Header()) if err != nil { return err } @@ -127,7 +127,7 @@ func (api *API) DeleteArgoTunnel(ctx context.Context, accountID, tunnelUUID stri func (api *API) CleanupArgoTunnelConnections(ctx context.Context, accountID, tunnelUUID string) error { uri := fmt.Sprintf("/accounts/%s/tunnels/%s/connections", accountID, tunnelUUID) - res, err := api.makeRequestContextWithHeaders(ctx, "DELETE", uri, nil, argoV1Header()) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodDelete, uri, nil, argoV1Header()) if err != nil { return err } diff --git a/argo_tunnel_test.go b/argo_tunnel_test.go index 9e33fa7c761..af71fe99f3c 100644 --- a/argo_tunnel_test.go +++ b/argo_tunnel_test.go @@ -15,7 +15,7 @@ func TestArgoTunnels(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -68,7 +68,7 @@ func TestArgoTunnel(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success":true, @@ -119,7 +119,7 @@ func TestCreateArgoTunnel(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success":true, @@ -170,7 +170,7 @@ func TestDeleteArgoTunnel(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success":true, @@ -204,7 +204,7 @@ func TestCleanupArgoTunnelConnections(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, diff --git a/auditlogs.go b/auditlogs.go index ad17d4df1c3..114ede5edbf 100644 --- a/auditlogs.go +++ b/auditlogs.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "path" "strconv" @@ -110,13 +112,13 @@ func (a AuditLogFilter) ToQuery() url.Values { // filtered based on any argument in the AuditLogFilter // // API Reference: https://api.cloudflare.com/#audit-logs-list-organization-audit-logs -func (api *API) GetOrganizationAuditLogs(organizationID string, a AuditLogFilter) (AuditLogResponse, error) { +func (api *API) GetOrganizationAuditLogs(ctx context.Context, organizationID string, a AuditLogFilter) (AuditLogResponse, error) { uri := url.URL{ Path: path.Join("/accounts", organizationID, "audit_logs"), ForceQuery: true, RawQuery: a.ToQuery().Encode(), } - res, err := api.makeRequest("GET", uri.String(), nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri.String(), nil) if err != nil { return AuditLogResponse{}, err } @@ -137,13 +139,13 @@ func unmarshalReturn(res []byte) (AuditLogResponse, error) { // filtered based on any argument in the AuditLogFilter // // API Reference: https://api.cloudflare.com/#audit-logs-list-user-audit-logs -func (api *API) GetUserAuditLogs(a AuditLogFilter) (AuditLogResponse, error) { +func (api *API) GetUserAuditLogs(ctx context.Context, a AuditLogFilter) (AuditLogResponse, error) { uri := url.URL{ Path: path.Join("/user", "audit_logs"), ForceQuery: true, RawQuery: a.ToQuery().Encode(), } - res, err := api.makeRequest("GET", uri.String(), nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri.String(), nil) if err != nil { return AuditLogResponse{}, err } diff --git a/authenticated_origin_pulls.go b/authenticated_origin_pulls.go index 28c3c744869..11f9c87802c 100644 --- a/authenticated_origin_pulls.go +++ b/authenticated_origin_pulls.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -24,9 +26,9 @@ type AuthenticatedOriginPullsResponse struct { // GetAuthenticatedOriginPullsStatus returns the configuration details for global AuthenticatedOriginPulls (tls_client_auth). // // API reference: https://api.cloudflare.com/#zone-settings-get-tls-client-auth-setting -func (api *API) GetAuthenticatedOriginPullsStatus(zoneID string) (AuthenticatedOriginPulls, error) { +func (api *API) GetAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string) (AuthenticatedOriginPulls, error) { uri := "/zones/" + zoneID + "/settings/tls_client_auth" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return AuthenticatedOriginPulls{}, err } @@ -40,7 +42,7 @@ func (api *API) GetAuthenticatedOriginPullsStatus(zoneID string) (AuthenticatedO // SetAuthenticatedOriginPullsStatus toggles whether global AuthenticatedOriginPulls is enabled for the zone. // // API reference: https://api.cloudflare.com/#zone-settings-change-tls-client-auth-setting -func (api *API) SetAuthenticatedOriginPullsStatus(zoneID string, enable bool) (AuthenticatedOriginPulls, error) { +func (api *API) SetAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string, enable bool) (AuthenticatedOriginPulls, error) { uri := "/zones/" + zoneID + "/settings/tls_client_auth" var val string if enable { @@ -53,7 +55,7 @@ func (api *API) SetAuthenticatedOriginPullsStatus(zoneID string, enable bool) (A }{ Value: val, } - res, err := api.makeRequest("PATCH", uri, params) + res, err := api.makeRequestContext(ctx, "PATCH", uri, params) if err != nil { return AuthenticatedOriginPulls{}, err } diff --git a/authenticated_origin_pulls_per_hostname.go b/authenticated_origin_pulls_per_hostname.go index c1b631c333c..235b9d47890 100644 --- a/authenticated_origin_pulls_per_hostname.go +++ b/authenticated_origin_pulls_per_hostname.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -76,9 +78,9 @@ type PerHostnameAuthenticatedOriginPullsConfigParams struct { // UploadPerHostnameAuthenticatedOriginPullsCertificate will upload the provided certificate and private key to the edge under Per Hostname AuthenticatedOriginPulls. // // API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-upload-a-hostname-client-certificate -func (api *API) UploadPerHostnameAuthenticatedOriginPullsCertificate(zoneID string, params PerHostnameAuthenticatedOriginPullsCertificateParams) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) UploadPerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID string, params PerHostnameAuthenticatedOriginPullsCertificateParams) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/hostnames/certificates" - res, err := api.makeRequest("POST", uri, params) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) if err != nil { return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err } @@ -92,9 +94,9 @@ func (api *API) UploadPerHostnameAuthenticatedOriginPullsCertificate(zoneID stri // GetPerHostnameAuthenticatedOriginPullsCertificate retrieves certificate metadata about the requested Per Hostname certificate. // // API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-get-the-hostname-client-certificate -func (api *API) GetPerHostnameAuthenticatedOriginPullsCertificate(zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) GetPerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/hostnames/certificates/" + certificateID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err } @@ -108,9 +110,9 @@ func (api *API) GetPerHostnameAuthenticatedOriginPullsCertificate(zoneID, certif // DeletePerHostnameAuthenticatedOriginPullsCertificate will remove the requested Per Hostname certificate from the edge. // // API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-delete-hostname-client-certificate -func (api *API) DeletePerHostnameAuthenticatedOriginPullsCertificate(zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) DeletePerHostnameAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerHostnameAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/hostnames/certificates/" + certificateID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return PerHostnameAuthenticatedOriginPullsCertificateDetails{}, err } @@ -124,12 +126,12 @@ func (api *API) DeletePerHostnameAuthenticatedOriginPullsCertificate(zoneID, cer // EditPerHostnameAuthenticatedOriginPullsConfig applies the supplied Per Hostname AuthenticatedOriginPulls config onto a hostname(s) in the edge. // // API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-enable-or-disable-a-hostname-for-client-authentication -func (api *API) EditPerHostnameAuthenticatedOriginPullsConfig(zoneID string, config []PerHostnameAuthenticatedOriginPullsConfig) ([]PerHostnameAuthenticatedOriginPullsDetails, error) { +func (api *API) EditPerHostnameAuthenticatedOriginPullsConfig(ctx context.Context, zoneID string, config []PerHostnameAuthenticatedOriginPullsConfig) ([]PerHostnameAuthenticatedOriginPullsDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/hostnames" conf := PerHostnameAuthenticatedOriginPullsConfigParams{ Config: config, } - res, err := api.makeRequest("PUT", uri, conf) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, conf) if err != nil { return []PerHostnameAuthenticatedOriginPullsDetails{}, err } @@ -143,9 +145,9 @@ func (api *API) EditPerHostnameAuthenticatedOriginPullsConfig(zoneID string, con // GetPerHostnameAuthenticatedOriginPullsConfig returns the config state of Per Hostname AuthenticatedOriginPulls of the provided hostname within a zone. // // API reference: https://api.cloudflare.com/#per-hostname-authenticated-origin-pull-get-the-hostname-status-for-client-authentication -func (api *API) GetPerHostnameAuthenticatedOriginPullsConfig(zoneID, hostname string) (PerHostnameAuthenticatedOriginPullsDetails, error) { +func (api *API) GetPerHostnameAuthenticatedOriginPullsConfig(ctx context.Context, zoneID, hostname string) (PerHostnameAuthenticatedOriginPullsDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/hostnames/" + hostname - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return PerHostnameAuthenticatedOriginPullsDetails{}, err } diff --git a/authenticated_origin_pulls_per_hostname_test.go b/authenticated_origin_pulls_per_hostname_test.go index f969ff3c6d9..3a1d900278a 100644 --- a/authenticated_origin_pulls_per_hostname_test.go +++ b/authenticated_origin_pulls_per_hostname_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -50,7 +51,7 @@ func TestUploadPerHostnameAuthenticatedOriginPullsCertificate(t *testing.T) { Certificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMHAwfXZ5/PWMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQwHhcNMTYwODI0MTY0MzAxWhcNMTYxMTIyMTY0MzAxWjBF\nMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50\nZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAwQHoetcl9+5ikGzV6cMzWtWPJHqXT3wpbEkRU9Yz7lgvddmGdtcGbg/1\nCGZu0jJGkMoppoUo4c3dts3iwqRYmBikUP77wwY2QGmDZw2FvkJCJlKnabIRuGvB\nKwzESIXgKk2016aTP6/dAjEHyo6SeoK8lkIySUvK0fyOVlsiEsCmOpidtnKX/a+5\n0GjB79CJH4ER2lLVZnhePFR/zUOyPxZQQ4naHf7yu/b5jhO0f8fwt+pyFxIXjbEI\ndZliWRkRMtzrHOJIhrmJ2A1J7iOrirbbwillwjjNVUWPf3IJ3M12S9pEewooaeO2\nizNTERcG9HzAacbVRn2Y2SWIyT/18QIDAQABo4GnMIGkMB0GA1UdDgQWBBT/LbE4\n9rWf288N6sJA5BRb6FJIGDB1BgNVHSMEbjBsgBT/LbE49rWf288N6sJA5BRb6FJI\nGKFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV\nBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAMHAwfXZ5/PWMAwGA1UdEwQF\nMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAHHFwl0tH0quUYZYO0dZYt4R7SJ0pCm2\n2satiyzHl4OnXcHDpekAo7/a09c6Lz6AU83cKy/+x3/djYHXWba7HpEu0dR3ugQP\nMlr4zrhd9xKZ0KZKiYmtJH+ak4OM4L3FbT0owUZPyjLSlhMtJVcoRp5CJsjAMBUG\nSvD8RX+T01wzox/Qb+lnnNnOlaWpqu8eoOenybxKp1a9ULzIVvN/LAcc+14vioFq\n2swRWtmocBAs8QR9n4uvbpiYvS8eYueDCWMM4fvFfBhaDZ3N9IbtySh3SpFdQDhw\nYbjM2rxXiyLGxB4Bol7QTv4zHif7Zt89FReT/NBy4rzaskDJY5L6xmY=\n-----END CERTIFICATE-----\n", PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAwQHoetcl9+5ikGzV6cMzWtWPJHqXT3wpbEkRU9Yz7lgvddmG\ndtcGbg/1CGZu0jJGkMoppoUo4c3dts3iwqRYmBikUP77wwY2QGmDZw2FvkJCJlKn\nabIRuGvBKwzESIXgKk2016aTP6/dAjEHyo6SeoK8lkIySUvK0fyOVlsiEsCmOpid\ntnKX/a+50GjB79CJH4ER2lLVZnhePFR/zUOyPxZQQ4naHf7yu/b5jhO0f8fwt+py\nFxIXjbEIdZliWRkRMtzrHOJIhrmJ2A1J7iOrirbbwillwjjNVUWPf3IJ3M12S9pE\newooaeO2izNTERcG9HzAacbVRn2Y2SWIyT/18QIDAQABAoIBACbhTYXBZYKmYPCb\nHBR1IBlCQA2nLGf0qRuJNJZg5iEzXows/6tc8YymZkQE7nolapWsQ+upk2y5Xdp/\naxiuprIs9JzkYK8Ox0r+dlwCG1kSW+UAbX0bQ/qUqlsTvU6muVuMP8vZYHxJ3wmb\n+ufRBKztPTQ/rYWaYQcgC0RWI20HTFBMxlTAyNxYNWzX7RKFkGVVyB9RsAtmcc8g\n+j4OdosbfNoJPS0HeIfNpAznDfHKdxDk2Yc1tV6RHBrC1ynyLE9+TaflIAdo2MVv\nKLMLq51GqYKtgJFIlBRPQqKoyXdz3fGvXrTkf/WY9QNq0J1Vk5ERePZ54mN8iZB7\n9lwy/AkCgYEA6FXzosxswaJ2wQLeoYc7ceaweX/SwTvxHgXzRyJIIT0eJWgx13Wo\n/WA3Iziimsjf6qE+SI/8laxPp2A86VMaIt3Z3mJN/CqSVGw8LK2AQst+OwdPyDMu\niacE8lj/IFGC8mwNUAb9CzGU3JpU4PxxGFjS/eMtGeRXCWkK4NE+G08CgYEA1Kp9\nN2JrVlqUz+gAX+LPmE9OEMAS9WQSQsfCHGogIFDGGcNf7+uwBM7GAaSJIP01zcoe\nVAgWdzXCv3FLhsaZoJ6RyLOLay5phbu1iaTr4UNYm5WtYTzMzqh8l1+MFFDl9xDB\nvULuCIIrglM5MeS/qnSg1uMoH2oVPj9TVst/ir8CgYEAxrI7Ws9Zc4Bt70N1As+U\nlySjaEVZCMkqvHJ6TCuVZFfQoE0r0whdLdRLU2PsLFP+q7qaeZQqgBaNSKeVcDYR\n9B+nY/jOmQoPewPVsp/vQTCnE/R81spu0mp0YI6cIheT1Z9zAy322svcc43JaWB7\nmEbeqyLOP4Z4qSOcmghZBSECgYACvR9Xs0DGn+wCsW4vze/2ei77MD4OQvepPIFX\ndFZtlBy5ADcgE9z0cuVB6CiL8DbdK5kwY9pGNr8HUCI03iHkW6Zs+0L0YmihfEVe\nPG19PSzK9CaDdhD9KFZSbLyVFmWfxOt50H7YRTTiPMgjyFpfi5j2q348yVT0tEQS\nfhRqaQKBgAcWPokmJ7EbYQGeMbS7HC8eWO/RyamlnSffdCdSc7ue3zdVJxpAkQ8W\nqu80pEIF6raIQfAf8MXiiZ7auFOSnHQTXUbhCpvDLKi0Mwq3G8Pl07l+2s6dQG6T\nlv6XTQaMyf6n1yjzL+fzDrH3qXMxHMO/b13EePXpDMpY7HQpoLDi\n-----END RSA PRIVATE KEY-----\n", } - actual, err := client.UploadPerHostnameAuthenticatedOriginPullsCertificate("023e105f4ecef8ad9ca31a8372d0c353", clientCert) + actual, err := client.UploadPerHostnameAuthenticatedOriginPullsCertificate(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", clientCert) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -93,7 +94,7 @@ func TestGetPerHostnameAuthenticatedOriginPullsCertificate(t *testing.T) { Status: "active", UploadedOn: uploadedOn, } - actual, err := client.GetPerHostnameAuthenticatedOriginPullsCertificate("023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") + actual, err := client.GetPerHostnameAuthenticatedOriginPullsCertificate(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -135,7 +136,7 @@ func TestDeletePerHostnameAuthenticatedOriginPullsCertificate(t *testing.T) { Status: "active", UploadedOn: uploadedOn, } - actual, err := client.DeletePerHostnameAuthenticatedOriginPullsCertificate("023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") + actual, err := client.DeletePerHostnameAuthenticatedOriginPullsCertificate(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -204,7 +205,7 @@ func TestEditPerHostnameAuthenticatedOriginPullsConfig(t *testing.T) { Enabled: true, }, } - actual, err := client.EditPerHostnameAuthenticatedOriginPullsConfig("023e105f4ecef8ad9ca31a8372d0c353", config) + actual, err := client.EditPerHostnameAuthenticatedOriginPullsConfig(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", config) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -261,7 +262,7 @@ func TestGetPerHostnameAuthenticatedOriginPullsConfig(t *testing.T) { CertUpdatedAt: certUpdatedAt, ExpiresOn: expiresOn, } - actual, err := client.GetPerHostnameAuthenticatedOriginPullsConfig("023e105f4ecef8ad9ca31a8372d0c353", "app.example.com") + actual, err := client.GetPerHostnameAuthenticatedOriginPullsConfig(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "app.example.com") if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/authenticated_origin_pulls_per_zone.go b/authenticated_origin_pulls_per_zone.go index c1c9015149b..64a6a49a2cb 100644 --- a/authenticated_origin_pulls_per_zone.go +++ b/authenticated_origin_pulls_per_zone.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -50,9 +52,9 @@ type PerZoneAuthenticatedOriginPullsCertificateParams struct { // GetPerZoneAuthenticatedOriginPullsStatus returns whether per zone AuthenticatedOriginPulls is enabled or not. It is false by default. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-get-enablement-setting-for-zone -func (api *API) GetPerZoneAuthenticatedOriginPullsStatus(zoneID string) (PerZoneAuthenticatedOriginPullsSettings, error) { +func (api *API) GetPerZoneAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string) (PerZoneAuthenticatedOriginPullsSettings, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/settings" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return PerZoneAuthenticatedOriginPullsSettings{}, err } @@ -66,14 +68,14 @@ func (api *API) GetPerZoneAuthenticatedOriginPullsStatus(zoneID string) (PerZone // SetPerZoneAuthenticatedOriginPullsStatus will update whether Per Zone AuthenticatedOriginPulls is enabled for the zone. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-set-enablement-for-zone -func (api *API) SetPerZoneAuthenticatedOriginPullsStatus(zoneID string, enable bool) (PerZoneAuthenticatedOriginPullsSettings, error) { +func (api *API) SetPerZoneAuthenticatedOriginPullsStatus(ctx context.Context, zoneID string, enable bool) (PerZoneAuthenticatedOriginPullsSettings, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/settings" params := struct { Enabled bool `json:"enabled"` }{ Enabled: enable, } - res, err := api.makeRequest("PUT", uri, params) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) if err != nil { return PerZoneAuthenticatedOriginPullsSettings{}, err } @@ -87,9 +89,9 @@ func (api *API) SetPerZoneAuthenticatedOriginPullsStatus(zoneID string, enable b // UploadPerZoneAuthenticatedOriginPullsCertificate will upload a provided client certificate and enable it to be used in all AuthenticatedOriginPulls requests for the zone. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-upload-certificate -func (api *API) UploadPerZoneAuthenticatedOriginPullsCertificate(zoneID string, params PerZoneAuthenticatedOriginPullsCertificateParams) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) UploadPerZoneAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID string, params PerZoneAuthenticatedOriginPullsCertificateParams) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth" - res, err := api.makeRequest("POST", uri, params) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) if err != nil { return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err } @@ -103,9 +105,9 @@ func (api *API) UploadPerZoneAuthenticatedOriginPullsCertificate(zoneID string, // ListPerZoneAuthenticatedOriginPullsCertificates returns a list of all user uploaded client certificates to Per Zone AuthenticatedOriginPulls. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-list-certificates -func (api *API) ListPerZoneAuthenticatedOriginPullsCertificates(zoneID string) ([]PerZoneAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) ListPerZoneAuthenticatedOriginPullsCertificates(ctx context.Context, zoneID string) ([]PerZoneAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []PerZoneAuthenticatedOriginPullsCertificateDetails{}, err } @@ -119,9 +121,9 @@ func (api *API) ListPerZoneAuthenticatedOriginPullsCertificates(zoneID string) ( // GetPerZoneAuthenticatedOriginPullsCertificateDetails returns the metadata associated with a user uploaded client certificate to Per Zone AuthenticatedOriginPulls. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-get-certificate-details -func (api *API) GetPerZoneAuthenticatedOriginPullsCertificateDetails(zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) GetPerZoneAuthenticatedOriginPullsCertificateDetails(ctx context.Context, zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/" + certificateID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err } @@ -135,9 +137,9 @@ func (api *API) GetPerZoneAuthenticatedOriginPullsCertificateDetails(zoneID, cer // DeletePerZoneAuthenticatedOriginPullsCertificate removes the specified client certificate from the edge. // // API reference: https://api.cloudflare.com/#zone-level-authenticated-origin-pulls-delete-certificate -func (api *API) DeletePerZoneAuthenticatedOriginPullsCertificate(zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { +func (api *API) DeletePerZoneAuthenticatedOriginPullsCertificate(ctx context.Context, zoneID, certificateID string) (PerZoneAuthenticatedOriginPullsCertificateDetails, error) { uri := "/zones/" + zoneID + "/origin_tls_client_auth/" + certificateID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return PerZoneAuthenticatedOriginPullsCertificateDetails{}, err } diff --git a/authenticated_origin_pulls_per_zone_test.go b/authenticated_origin_pulls_per_zone_test.go index 8c7eb3b4836..2f53a2b7098 100644 --- a/authenticated_origin_pulls_per_zone_test.go +++ b/authenticated_origin_pulls_per_zone_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -28,7 +29,7 @@ func TestGetPerZoneAuthenticatedOriginPullsStatus(t *testing.T) { want := PerZoneAuthenticatedOriginPullsSettings{ Enabled: true, } - actual, err := client.GetPerZoneAuthenticatedOriginPullsStatus("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.GetPerZoneAuthenticatedOriginPullsStatus(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -53,7 +54,7 @@ func TestSetPerZoneAuthenticatedOriginPullsStatus(t *testing.T) { want := PerZoneAuthenticatedOriginPullsSettings{ Enabled: true, } - actual, err := client.SetPerZoneAuthenticatedOriginPullsStatus("023e105f4ecef8ad9ca31a8372d0c353", true) + actual, err := client.SetPerZoneAuthenticatedOriginPullsStatus(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", true) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -98,7 +99,7 @@ func TestUploadPerZoneAuthenticatedOriginPullsCertificate(t *testing.T) { Certificate: "-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMHAwfXZ5/PWMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\nBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX\naWRnaXRzIFB0eSBMdGQwHhcNMTYwODI0MTY0MzAxWhcNMTYxMTIyMTY0MzAxWjBF\nMQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50\nZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAwQHoetcl9+5ikGzV6cMzWtWPJHqXT3wpbEkRU9Yz7lgvddmGdtcGbg/1\nCGZu0jJGkMoppoUo4c3dts3iwqRYmBikUP77wwY2QGmDZw2FvkJCJlKnabIRuGvB\nKwzESIXgKk2016aTP6/dAjEHyo6SeoK8lkIySUvK0fyOVlsiEsCmOpidtnKX/a+5\n0GjB79CJH4ER2lLVZnhePFR/zUOyPxZQQ4naHf7yu/b5jhO0f8fwt+pyFxIXjbEI\ndZliWRkRMtzrHOJIhrmJ2A1J7iOrirbbwillwjjNVUWPf3IJ3M12S9pEewooaeO2\nizNTERcG9HzAacbVRn2Y2SWIyT/18QIDAQABo4GnMIGkMB0GA1UdDgQWBBT/LbE4\n9rWf288N6sJA5BRb6FJIGDB1BgNVHSMEbjBsgBT/LbE49rWf288N6sJA5BRb6FJI\nGKFJpEcwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV\nBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAMHAwfXZ5/PWMAwGA1UdEwQF\nMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAHHFwl0tH0quUYZYO0dZYt4R7SJ0pCm2\n2satiyzHl4OnXcHDpekAo7/a09c6Lz6AU83cKy/+x3/djYHXWba7HpEu0dR3ugQP\nMlr4zrhd9xKZ0KZKiYmtJH+ak4OM4L3FbT0owUZPyjLSlhMtJVcoRp5CJsjAMBUG\nSvD8RX+T01wzox/Qb+lnnNnOlaWpqu8eoOenybxKp1a9ULzIVvN/LAcc+14vioFq\n2swRWtmocBAs8QR9n4uvbpiYvS8eYueDCWMM4fvFfBhaDZ3N9IbtySh3SpFdQDhw\nYbjM2rxXiyLGxB4Bol7QTv4zHif7Zt89FReT/NBy4rzaskDJY5L6xmY=\n-----END CERTIFICATE-----\n", PrivateKey: "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAwQHoetcl9+5ikGzV6cMzWtWPJHqXT3wpbEkRU9Yz7lgvddmG\ndtcGbg/1CGZu0jJGkMoppoUo4c3dts3iwqRYmBikUP77wwY2QGmDZw2FvkJCJlKn\nabIRuGvBKwzESIXgKk2016aTP6/dAjEHyo6SeoK8lkIySUvK0fyOVlsiEsCmOpid\ntnKX/a+50GjB79CJH4ER2lLVZnhePFR/zUOyPxZQQ4naHf7yu/b5jhO0f8fwt+py\nFxIXjbEIdZliWRkRMtzrHOJIhrmJ2A1J7iOrirbbwillwjjNVUWPf3IJ3M12S9pE\newooaeO2izNTERcG9HzAacbVRn2Y2SWIyT/18QIDAQABAoIBACbhTYXBZYKmYPCb\nHBR1IBlCQA2nLGf0qRuJNJZg5iEzXows/6tc8YymZkQE7nolapWsQ+upk2y5Xdp/\naxiuprIs9JzkYK8Ox0r+dlwCG1kSW+UAbX0bQ/qUqlsTvU6muVuMP8vZYHxJ3wmb\n+ufRBKztPTQ/rYWaYQcgC0RWI20HTFBMxlTAyNxYNWzX7RKFkGVVyB9RsAtmcc8g\n+j4OdosbfNoJPS0HeIfNpAznDfHKdxDk2Yc1tV6RHBrC1ynyLE9+TaflIAdo2MVv\nKLMLq51GqYKtgJFIlBRPQqKoyXdz3fGvXrTkf/WY9QNq0J1Vk5ERePZ54mN8iZB7\n9lwy/AkCgYEA6FXzosxswaJ2wQLeoYc7ceaweX/SwTvxHgXzRyJIIT0eJWgx13Wo\n/WA3Iziimsjf6qE+SI/8laxPp2A86VMaIt3Z3mJN/CqSVGw8LK2AQst+OwdPyDMu\niacE8lj/IFGC8mwNUAb9CzGU3JpU4PxxGFjS/eMtGeRXCWkK4NE+G08CgYEA1Kp9\nN2JrVlqUz+gAX+LPmE9OEMAS9WQSQsfCHGogIFDGGcNf7+uwBM7GAaSJIP01zcoe\nVAgWdzXCv3FLhsaZoJ6RyLOLay5phbu1iaTr4UNYm5WtYTzMzqh8l1+MFFDl9xDB\nvULuCIIrglM5MeS/qnSg1uMoH2oVPj9TVst/ir8CgYEAxrI7Ws9Zc4Bt70N1As+U\nlySjaEVZCMkqvHJ6TCuVZFfQoE0r0whdLdRLU2PsLFP+q7qaeZQqgBaNSKeVcDYR\n9B+nY/jOmQoPewPVsp/vQTCnE/R81spu0mp0YI6cIheT1Z9zAy322svcc43JaWB7\nmEbeqyLOP4Z4qSOcmghZBSECgYACvR9Xs0DGn+wCsW4vze/2ei77MD4OQvepPIFX\ndFZtlBy5ADcgE9z0cuVB6CiL8DbdK5kwY9pGNr8HUCI03iHkW6Zs+0L0YmihfEVe\nPG19PSzK9CaDdhD9KFZSbLyVFmWfxOt50H7YRTTiPMgjyFpfi5j2q348yVT0tEQS\nfhRqaQKBgAcWPokmJ7EbYQGeMbS7HC8eWO/RyamlnSffdCdSc7ue3zdVJxpAkQ8W\nqu80pEIF6raIQfAf8MXiiZ7auFOSnHQTXUbhCpvDLKi0Mwq3G8Pl07l+2s6dQG6T\nlv6XTQaMyf6n1yjzL+fzDrH3qXMxHMO/b13EePXpDMpY7HQpoLDi\n-----END RSA PRIVATE KEY-----\n", } - actual, err := client.UploadPerZoneAuthenticatedOriginPullsCertificate("023e105f4ecef8ad9ca31a8372d0c353", clientCert) + actual, err := client.UploadPerZoneAuthenticatedOriginPullsCertificate(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", clientCert) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -142,7 +143,7 @@ func TestListPerZoneAuthenticatedOriginPullsCertificates(t *testing.T) { UploadedOn: uploadedOn, }, } - actual, err := client.ListPerZoneAuthenticatedOriginPullsCertificates("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.ListPerZoneAuthenticatedOriginPullsCertificates(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -182,7 +183,7 @@ func TestGetPerZoneAuthenticatedOriginPullsCertificateDetails(t *testing.T) { Status: "active", UploadedOn: uploadedOn, } - actual, err := client.GetPerZoneAuthenticatedOriginPullsCertificateDetails("023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") + actual, err := client.GetPerZoneAuthenticatedOriginPullsCertificateDetails(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -222,7 +223,7 @@ func TestDeletePerZoneAuthenticatedOriginPullsCertificate(t *testing.T) { Status: "active", UploadedOn: uploadedOn, } - actual, err := client.DeletePerZoneAuthenticatedOriginPullsCertificate("023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") + actual, err := client.DeletePerZoneAuthenticatedOriginPullsCertificate(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "2458ce5a-0c35-4c7f-82c7-8e9487d3ff60") if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/authenticated_origin_pulls_test.go b/authenticated_origin_pulls_test.go index 460bdd8ce00..703270055bf 100644 --- a/authenticated_origin_pulls_test.go +++ b/authenticated_origin_pulls_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -37,7 +38,7 @@ func TestAuthenticatedOriginPullsDetails(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.GetAuthenticatedOriginPullsStatus("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.GetAuthenticatedOriginPullsStatus(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -70,7 +71,7 @@ func TestSetAuthenticatedOriginPullsStatusEnabled(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.SetAuthenticatedOriginPullsStatus("023e105f4ecef8ad9ca31a8372d0c353", true) + actual, err := client.SetAuthenticatedOriginPullsStatus(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", true) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -103,7 +104,7 @@ func TestSetAuthenticatedOriginPullsStatusDisabled(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.SetAuthenticatedOriginPullsStatus("023e105f4ecef8ad9ca31a8372d0c353", false) + actual, err := client.SetAuthenticatedOriginPullsStatus(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", false) if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/certificate_packs.go b/certificate_packs.go index b5600e11ac8..0cedbcb60c8 100644 --- a/certificate_packs.go +++ b/certificate_packs.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "encoding/json" "fmt" "net/http" @@ -83,9 +84,9 @@ type CertificatePacksAdvancedDetailResponse struct { // ListCertificatePacks returns all available TLS certificate packs for a zone. // // API Reference: https://api.cloudflare.com/#certificate-packs-list-certificate-packs -func (api *API) ListCertificatePacks(zoneID string) ([]CertificatePack, error) { +func (api *API) ListCertificatePacks(ctx context.Context, zoneID string) ([]CertificatePack, error) { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs?status=all", zoneID) - res, err := api.makeRequest(http.MethodGet, uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []CertificatePack{}, err } @@ -102,9 +103,9 @@ func (api *API) ListCertificatePacks(zoneID string) ([]CertificatePack, error) { // CertificatePack returns a single TLS certificate pack on a zone. // // API Reference: https://api.cloudflare.com/#certificate-packs-get-certificate-pack -func (api *API) CertificatePack(zoneID, certificatePackID string) (CertificatePack, error) { +func (api *API) CertificatePack(ctx context.Context, zoneID, certificatePackID string) (CertificatePack, error) { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificatePackID) - res, err := api.makeRequest(http.MethodGet, uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return CertificatePack{}, err } @@ -121,9 +122,9 @@ func (api *API) CertificatePack(zoneID, certificatePackID string) (CertificatePa // CreateCertificatePack creates a new certificate pack associated with a zone. // // API Reference: https://api.cloudflare.com/#certificate-packs-order-certificate-pack -func (api *API) CreateCertificatePack(zoneID string, cert CertificatePackRequest) (CertificatePack, error) { +func (api *API) CreateCertificatePack(ctx context.Context, zoneID string, cert CertificatePackRequest) (CertificatePack, error) { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs", zoneID) - res, err := api.makeRequest(http.MethodPost, uri, cert) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, cert) if err != nil { return CertificatePack{}, err } @@ -140,9 +141,9 @@ func (api *API) CreateCertificatePack(zoneID string, cert CertificatePackRequest // DeleteCertificatePack removes a certificate pack associated with a zone. // // API Reference: https://api.cloudflare.com/#certificate-packs-delete-advanced-certificate-manager-certificate-pack -func (api *API) DeleteCertificatePack(zoneID, certificateID string) error { +func (api *API) DeleteCertificatePack(ctx context.Context, zoneID, certificateID string) error { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificateID) - _, err := api.makeRequest(http.MethodDelete, uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -153,9 +154,9 @@ func (api *API) DeleteCertificatePack(zoneID, certificateID string) error { // CreateAdvancedCertificatePack creates a new certificate pack associated with a zone. // // API Reference: https://api.cloudflare.com/#certificate-packs-order-certificate-pack -func (api *API) CreateAdvancedCertificatePack(zoneID string, cert CertificatePackAdvancedCertificate) (CertificatePackAdvancedCertificate, error) { +func (api *API) CreateAdvancedCertificatePack(ctx context.Context, zoneID string, cert CertificatePackAdvancedCertificate) (CertificatePackAdvancedCertificate, error) { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/order", zoneID) - res, err := api.makeRequest(http.MethodPost, uri, cert) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, cert) if err != nil { return CertificatePackAdvancedCertificate{}, err } @@ -173,9 +174,9 @@ func (api *API) CreateAdvancedCertificatePack(zoneID string, cert CertificatePac // pending certificate pack. // // API Reference: https://api.cloudflare.com/#certificate-packs-restart-validation-for-advanced-certificate-manager-certificate-pack -func (api *API) RestartAdvancedCertificateValidation(zoneID, certificateID string) (CertificatePackAdvancedCertificate, error) { +func (api *API) RestartAdvancedCertificateValidation(ctx context.Context, zoneID, certificateID string) (CertificatePackAdvancedCertificate, error) { uri := fmt.Sprintf("/zones/%s/ssl/certificate_packs/%s", zoneID, certificateID) - res, err := api.makeRequest(http.MethodPatch, uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, nil) if err != nil { return CertificatePackAdvancedCertificate{}, err } diff --git a/certificate_packs_test.go b/certificate_packs_test.go index fd814e6fc07..de077f9ca28 100644 --- a/certificate_packs_test.go +++ b/certificate_packs_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -40,7 +41,7 @@ func TestListCertificatePacks(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -85,7 +86,7 @@ func TestListCertificatePacks(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/ssl/certificate_packs", handler) want := []CertificatePack{desiredCertificatePack} - actual, err := client.ListCertificatePacks("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.ListCertificatePacks(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -97,7 +98,7 @@ func TestListCertificatePack(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -139,7 +140,7 @@ func TestListCertificatePack(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/ssl/certificate_packs/3822ff90-ea29-44df-9e55-21300bb9419b", handler) - actual, err := client.CertificatePack("023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") + actual, err := client.CertificatePack(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") if assert.NoError(t, err) { assert.Equal(t, desiredCertificatePack, actual) @@ -151,7 +152,7 @@ func TestCreateCertificatePack(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -194,7 +195,7 @@ func TestCreateCertificatePack(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/ssl/certificate_packs", handler) certificate := CertificatePackRequest{Type: "custom", Hosts: []string{"example.com", "*.example.com", "www.example.com"}} - actual, err := client.CreateCertificatePack("023e105f4ecef8ad9ca31a8372d0c353", certificate) + actual, err := client.CreateCertificatePack(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", certificate) if assert.NoError(t, err) { assert.Equal(t, desiredCertificatePack, actual) @@ -206,7 +207,7 @@ func TestCreateAdvancedCertificatePack(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -241,7 +242,7 @@ func TestCreateAdvancedCertificatePack(t *testing.T) { CloudflareBranding: false, } - actual, err := client.CreateAdvancedCertificatePack("023e105f4ecef8ad9ca31a8372d0c353", certificate) + actual, err := client.CreateAdvancedCertificatePack(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", certificate) if assert.NoError(t, err) { assert.Equal(t, certificate, actual) @@ -288,7 +289,7 @@ func TestRestartAdvancedCertificateValidation(t *testing.T) { CloudflareBranding: false, } - actual, err := client.RestartAdvancedCertificateValidation("023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") + actual, err := client.RestartAdvancedCertificateValidation(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") if assert.NoError(t, err) { assert.Equal(t, certificate, actual) @@ -300,7 +301,7 @@ func TestDeleteCertificatePack(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -315,7 +316,7 @@ func TestDeleteCertificatePack(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/ssl/certificate_packs/3822ff90-ea29-44df-9e55-21300bb9419b", handler) - err := client.DeleteCertificatePack("023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") + err := client.DeleteCertificatePack(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "3822ff90-ea29-44df-9e55-21300bb9419b") assert.NoError(t, err) } diff --git a/cloudflare_test.go b/cloudflare_test.go index 65ab88dd5bc..173a202892c 100644 --- a/cloudflare_test.go +++ b/cloudflare_test.go @@ -43,12 +43,12 @@ func TestClient_Headers(t *testing.T) { // it should set default headers setup() mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Equal(t, "cloudflare@example.org", r.Header.Get("X-Auth-Email")) assert.Equal(t, "deadbeef", r.Header.Get("X-Auth-Key")) assert.Equal(t, "application/json", r.Header.Get("Content-Type")) }) - client.UserDetails() + client.UserDetails(context.TODO()) teardown() // it should override appropriate default headers when custom headers given @@ -57,13 +57,13 @@ func TestClient_Headers(t *testing.T) { headers.Add("X-Random", "a random header") setup(Headers(headers)) mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Equal(t, "cloudflare@example.org", r.Header.Get("X-Auth-Email")) assert.Equal(t, "deadbeef", r.Header.Get("X-Auth-Key")) assert.Equal(t, "application/xhtml+xml", r.Header.Get("Content-Type")) assert.Equal(t, "a random header", r.Header.Get("X-Random")) }) - client.UserDetails() + client.UserDetails(context.TODO()) teardown() // it should set X-Auth-User-Service-Key and omit X-Auth-Email and X-Auth-Key when client.authType is AuthUserService @@ -71,14 +71,14 @@ func TestClient_Headers(t *testing.T) { client.SetAuthType(AuthUserService) client.APIUserServiceKey = "userservicekey" mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Empty(t, r.Header.Get("X-Auth-Email")) assert.Empty(t, r.Header.Get("X-Auth-Key")) assert.Empty(t, r.Header.Get("Authorization")) assert.Equal(t, "userservicekey", r.Header.Get("X-Auth-User-Service-Key")) assert.Equal(t, "application/json", r.Header.Get("Content-Type")) }) - client.UserDetails() + client.UserDetails(context.TODO()) teardown() // it should set X-Auth-User-Service-Key and omit X-Auth-Email and X-Auth-Key when using NewWithUserServiceKey @@ -87,14 +87,14 @@ func TestClient_Headers(t *testing.T) { assert.NoError(t, err) client.BaseURL = server.URL mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Empty(t, r.Header.Get("X-Auth-Email")) assert.Empty(t, r.Header.Get("X-Auth-Key")) assert.Empty(t, r.Header.Get("Authorization")) assert.Equal(t, "userservicekey", r.Header.Get("X-Auth-User-Service-Key")) assert.Equal(t, "application/json", r.Header.Get("Content-Type")) }) - client.UserDetails() + client.UserDetails(context.TODO()) teardown() // it should set Authorization and omit others credential headers when using NewWithAPIToken @@ -103,14 +103,14 @@ func TestClient_Headers(t *testing.T) { assert.NoError(t, err) client.BaseURL = server.URL mux.HandleFunc("/zones/123456", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Empty(t, r.Header.Get("X-Auth-Email")) assert.Empty(t, r.Header.Get("X-Auth-Key")) assert.Empty(t, r.Header.Get("X-Auth-User-Service-Key")) assert.Equal(t, "Bearer my-api-token", r.Header.Get("Authorization")) assert.Equal(t, "application/json", r.Header.Get("Content-Type")) }) - client.UserDetails() + client.UserDetails(context.TODO()) teardown() } @@ -121,7 +121,7 @@ func TestClient_RetryCanSucceedAfterErrors(t *testing.T) { requestsReceived := 0 // could test any function, using ListLoadBalancerPools handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // we are doing three *retries* @@ -182,7 +182,7 @@ func TestClient_RetryCanSucceedAfterErrors(t *testing.T) { mux.HandleFunc("/user/load_balancers/pools", handler) - _, err := client.ListLoadBalancerPools() + _, err := client.ListLoadBalancerPools(context.TODO()) assert.NoError(t, err) } @@ -192,7 +192,7 @@ func TestClient_RetryReturnsPersistentErrorResponse(t *testing.T) { // could test any function, using ListLoadBalancerPools handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // return error causing client to retry @@ -208,7 +208,7 @@ func TestClient_RetryReturnsPersistentErrorResponse(t *testing.T) { mux.HandleFunc("/user/load_balancers/pools", handler) - _, err := client.ListLoadBalancerPools() + _, err := client.ListLoadBalancerPools(context.TODO()) assert.Error(t, err) } @@ -217,7 +217,7 @@ func TestZoneIDByNameWithNonUniqueZonesWithoutOrgID(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -355,7 +355,7 @@ func TestZoneIDByNameWithNonUniqueZonesWithOrgId(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -495,7 +495,7 @@ func TestZoneIDByNameWithIDN(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -662,7 +662,7 @@ func TestErrorFromResponse(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") w.WriteHeader(403) fmt.Fprintf(w, `{ @@ -676,14 +676,11 @@ func TestErrorFromResponse(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/access/apps", handler) - _, err := client.CreateAccessApplication( - "01a7362d577a6c3019a474fd6f485823", - AccessApplication{ - Name: "Admin Site", - Domain: "test.example.com/admin", - SessionDuration: "24h", - }, - ) + _, err := client.CreateAccessApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", AccessApplication{ + Name: "Admin Site", + Domain: "test.example.com/admin", + SessionDuration: "24h", + }) assert.EqualError(t, err, "HTTP status 403: this is a test error (9999)") } diff --git a/cmd/flarectl/dns.go b/cmd/flarectl/dns.go index 86840bfbfdb..3b131252346 100644 --- a/cmd/flarectl/dns.go +++ b/cmd/flarectl/dns.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "os" "strconv" @@ -18,7 +19,7 @@ func formatDNSRecord(record cloudflare.DNSRecord) []string { record.Content, strconv.FormatInt(int64(record.TTL), 10), strconv.FormatBool(record.Proxiable), - strconv.FormatBool(record.Proxied), + strconv.FormatBool(*record.Proxied), strconv.FormatBool(record.Locked), } } @@ -45,9 +46,9 @@ func dnsCreate(c *cli.Context) error { Type: strings.ToUpper(rtype), Content: content, TTL: ttl, - Proxied: proxy, + Proxied: &proxy, } - resp, err := api.CreateDNSRecord(zoneID, record) + resp, err := api.CreateDNSRecord(context.TODO(), zoneID, record) if err != nil { fmt.Fprintln(os.Stderr, "Error creating DNS record: ", err) return err @@ -84,7 +85,7 @@ func dnsCreateOrUpdate(c *cli.Context) error { rr := cloudflare.DNSRecord{ Name: name + "." + zone, } - records, err := api.DNSRecords(zoneID, rr) + records, err := api.DNSRecords(context.TODO(), zoneID, rr) if err != nil { fmt.Fprintln(os.Stderr, "Error fetching DNS records: ", err) return err @@ -101,8 +102,9 @@ func dnsCreateOrUpdate(c *cli.Context) error { rr.Type = r.Type rr.Content = content rr.TTL = ttl - rr.Proxied = proxy - err := api.UpdateDNSRecord(zoneID, r.ID, rr) + rr.Proxied = &proxy + + err := api.UpdateDNSRecord(context.TODO(), zoneID, r.ID, rr) if err != nil { fmt.Println("Error updating DNS record:", err) return err @@ -117,9 +119,9 @@ func dnsCreateOrUpdate(c *cli.Context) error { rr.Type = rtype rr.Content = content rr.TTL = ttl - rr.Proxied = proxy + rr.Proxied = &proxy // TODO: Print the response. - resp, err = api.CreateDNSRecord(zoneID, rr) + resp, err = api.CreateDNSRecord(context.TODO(), zoneID, rr) if err != nil { fmt.Println("Error creating DNS record:", err) return err @@ -161,9 +163,9 @@ func dnsUpdate(c *cli.Context) error { Type: strings.ToUpper(rtype), Content: content, TTL: ttl, - Proxied: proxy, + Proxied: &proxy, } - err = api.UpdateDNSRecord(zoneID, recordID, record) + err = api.UpdateDNSRecord(context.TODO(), zoneID, recordID, record) if err != nil { fmt.Fprintln(os.Stderr, "Error updating DNS record: ", err) return err @@ -186,7 +188,7 @@ func dnsDelete(c *cli.Context) error { return err } - err = api.DeleteDNSRecord(zoneID, recordID) + err = api.DeleteDNSRecord(context.TODO(), zoneID, recordID) if err != nil { fmt.Fprintln(os.Stderr, "Error deleting DNS record: ", err) return err diff --git a/cmd/flarectl/firewall.go b/cmd/flarectl/firewall.go index e34b6e9dfce..68cc2ce04ce 100644 --- a/cmd/flarectl/firewall.go +++ b/cmd/flarectl/firewall.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "net" "os" @@ -45,11 +46,11 @@ func firewallAccessRules(c *cli.Context) error { var response *cloudflare.AccessRuleListResponse switch { case accountID != "": - response, err = api.ListAccountAccessRules(accountID, rule, 1) + response, err = api.ListAccountAccessRules(context.TODO(), accountID, rule, 1) case zoneID != "": - response, err = api.ListZoneAccessRules(zoneID, rule, 1) + response, err = api.ListZoneAccessRules(context.TODO(), zoneID, rule, 1) default: - response, err = api.ListUserAccessRules(rule, 1) + response, err = api.ListUserAccessRules(context.TODO(), rule, 1) } if err != nil { fmt.Println(err) @@ -62,11 +63,11 @@ func firewallAccessRules(c *cli.Context) error { for page := 2; page <= totalPages; page++ { switch { case accountID != "": - response, err = api.ListAccountAccessRules(accountID, rule, page) + response, err = api.ListAccountAccessRules(context.TODO(), accountID, rule, page) case zoneID != "": - response, err = api.ListZoneAccessRules(zoneID, rule, page) + response, err = api.ListZoneAccessRules(context.TODO(), zoneID, rule, page) default: - response, err = api.ListUserAccessRules(rule, page) + response, err = api.ListUserAccessRules(context.TODO(), rule, page) } if err != nil { fmt.Println(err) @@ -110,21 +111,21 @@ func firewallAccessRuleCreate(c *cli.Context) error { switch { case accountID != "": - resp, err := api.CreateAccountAccessRule(accountID, rule) + resp, err := api.CreateAccountAccessRule(context.TODO(), accountID, rule) if err != nil { fmt.Fprintln(os.Stderr, "error creating account access rule: ", err) return err } rules = append(rules, resp.Result) case zoneID != "": - resp, err := api.CreateZoneAccessRule(zoneID, rule) + resp, err := api.CreateZoneAccessRule(context.TODO(), zoneID, rule) if err != nil { fmt.Fprintln(os.Stderr, "error creating zone access rule: ", err) return err } rules = append(rules, resp.Result) default: - resp, err := api.CreateUserAccessRule(rule) + resp, err := api.CreateUserAccessRule(context.TODO(), rule) if err != nil { fmt.Fprintln(os.Stderr, "error creating user access rule: ", err) return err @@ -166,19 +167,19 @@ func firewallAccessRuleUpdate(c *cli.Context) error { ) switch { case accountID != "": - resp, err := api.UpdateAccountAccessRule(accountID, id, rule) + resp, err := api.UpdateAccountAccessRule(context.TODO(), accountID, id, rule) if err != nil { errors.Wrap(err, errUpdating) } rules = append(rules, resp.Result) case zoneID != "": - resp, err := api.UpdateZoneAccessRule(zoneID, id, rule) + resp, err := api.UpdateZoneAccessRule(context.TODO(), zoneID, id, rule) if err != nil { errors.Wrap(err, errUpdating) } rules = append(rules, resp.Result) default: - resp, err := api.UpdateUserAccessRule(id, rule) + resp, err := api.UpdateUserAccessRule(context.TODO(), id, rule) if err != nil { errors.Wrap(err, errUpdating) } @@ -214,11 +215,11 @@ func firewallAccessRuleCreateOrUpdate(c *cli.Context) error { var response *cloudflare.AccessRuleListResponse switch { case accountID != "": - response, err = api.ListAccountAccessRules(accountID, rule, 1) + response, err = api.ListAccountAccessRules(context.TODO(), accountID, rule, 1) case zoneID != "": - response, err = api.ListZoneAccessRules(zoneID, rule, 1) + response, err = api.ListZoneAccessRules(context.TODO(), zoneID, rule, 1) default: - response, err = api.ListUserAccessRules(rule, 1) + response, err = api.ListUserAccessRules(context.TODO(), rule, 1) } if err != nil { fmt.Println("Error creating or updating firewall access rule:", err) @@ -237,11 +238,11 @@ func firewallAccessRuleCreateOrUpdate(c *cli.Context) error { } switch { case accountID != "": - _, err = api.UpdateAccountAccessRule(accountID, r.ID, rule) + _, err = api.UpdateAccountAccessRule(context.TODO(), accountID, r.ID, rule) case zoneID != "": - _, err = api.UpdateZoneAccessRule(zoneID, r.ID, rule) + _, err = api.UpdateZoneAccessRule(context.TODO(), zoneID, r.ID, rule) default: - _, err = api.UpdateUserAccessRule(r.ID, rule) + _, err = api.UpdateUserAccessRule(context.TODO(), r.ID, rule) } if err != nil { fmt.Println("Error updating firewall access rule:", err) @@ -250,11 +251,11 @@ func firewallAccessRuleCreateOrUpdate(c *cli.Context) error { } else { switch { case accountID != "": - _, err = api.CreateAccountAccessRule(accountID, rule) + _, err = api.CreateAccountAccessRule(context.TODO(), accountID, rule) case zoneID != "": - _, err = api.CreateZoneAccessRule(zoneID, rule) + _, err = api.CreateZoneAccessRule(context.TODO(), zoneID, rule) default: - _, err = api.CreateUserAccessRule(rule) + _, err = api.CreateUserAccessRule(context.TODO(), rule) } if err != nil { fmt.Println("Error creating firewall access rule:", err) @@ -282,19 +283,19 @@ func firewallAccessRuleDelete(c *cli.Context) error { ) switch { case accountID != "": - resp, err := api.DeleteAccountAccessRule(accountID, ruleID) + resp, err := api.DeleteAccountAccessRule(context.TODO(), accountID, ruleID) if err != nil { errors.Wrap(err, errDeleting) } rules = append(rules, resp.Result) case zoneID != "": - resp, err := api.DeleteZoneAccessRule(zoneID, ruleID) + resp, err := api.DeleteZoneAccessRule(context.TODO(), zoneID, ruleID) if err != nil { errors.Wrap(err, errDeleting) } rules = append(rules, resp.Result) default: - resp, err := api.DeleteUserAccessRule(ruleID) + resp, err := api.DeleteUserAccessRule(context.TODO(), ruleID) if err != nil { errors.Wrap(err, errDeleting) } @@ -318,7 +319,7 @@ func getScope(c *cli.Context) (string, string, error) { if c.String("account") != "" { account = c.String("account") pageOpts := cloudflare.PaginationOptions{} - accounts, _, err := api.Accounts(pageOpts) + accounts, _, err := api.Accounts(context.TODO(), pageOpts) if err != nil { fmt.Println(err) return "", "", err diff --git a/cmd/flarectl/flarectl.go b/cmd/flarectl/flarectl.go index d8821174f62..4efdb952223 100644 --- a/cmd/flarectl/flarectl.go +++ b/cmd/flarectl/flarectl.go @@ -8,10 +8,10 @@ import ( ) var ( - version = "dev" - commit = "none" - date = "unknown" - builtBy = "unknown" + version = "dev" + commit = "none" + date = "unknown" + builtBy = "unknown" ) var api *cloudflare.API @@ -23,9 +23,9 @@ func main() { app.Version = version app.Flags = []cli.Flag{ &cli.StringFlag{ - Name: "account-id", - Usage: "Optional account ID", - Value: "", + Name: "account-id", + Usage: "Optional account ID", + Value: "", EnvVars: []string{"CF_ACCOUNT_ID"}, }, &cli.BoolFlag{ diff --git a/cmd/flarectl/misc.go b/cmd/flarectl/misc.go index 667a0124149..85ab50eb639 100644 --- a/cmd/flarectl/misc.go +++ b/cmd/flarectl/misc.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "fmt" "os" @@ -138,7 +139,7 @@ func _getIps(ipType string, showMsgType bool) { } func userInfo(c *cli.Context) error { - user, err := api.UserDetails() + user, err := api.UserDetails(context.TODO()) if err != nil { fmt.Println(err) return err @@ -172,7 +173,7 @@ func pageRules(c *cli.Context) error { return err } - rules, err := api.ListPageRules(zoneID) + rules, err := api.ListPageRules(context.TODO(), zoneID) if err != nil { fmt.Println(err) return err diff --git a/cmd/flarectl/user_agent.go b/cmd/flarectl/user_agent.go index cf83c01fe45..bb67a3acc6d 100644 --- a/cmd/flarectl/user_agent.go +++ b/cmd/flarectl/user_agent.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "os" "strconv" @@ -41,7 +42,7 @@ func userAgentCreate(c *cli.Context) error { }, } - resp, err := api.CreateUserAgentRule(zoneID, userAgentRule) + resp, err := api.CreateUserAgentRule(context.TODO(), zoneID, userAgentRule) if err != nil { fmt.Fprintln(os.Stderr, "Error creating User-Agent block rule: ", err) return err @@ -77,7 +78,7 @@ func userAgentUpdate(c *cli.Context) error { }, } - resp, err := api.UpdateUserAgentRule(zoneID, c.String("id"), userAgentRule) + resp, err := api.UpdateUserAgentRule(context.TODO(), zoneID, c.String("id"), userAgentRule) if err != nil { fmt.Fprintln(os.Stderr, "Error updating User-Agent block rule: ", err) return err @@ -103,7 +104,7 @@ func userAgentDelete(c *cli.Context) error { return err } - resp, err := api.DeleteUserAgentRule(zoneID, c.String("id")) + resp, err := api.DeleteUserAgentRule(context.TODO(), zoneID, c.String("id")) if err != nil { fmt.Fprintln(os.Stderr, "Error deleting User-Agent block rule: ", err) return err @@ -129,7 +130,7 @@ func userAgentList(c *cli.Context) error { return err } - resp, err := api.ListUserAgentRules(zoneID, c.Int("page")) + resp, err := api.ListUserAgentRules(context.TODO(), zoneID, c.Int("page")) if err != nil { fmt.Fprintln(os.Stderr, "Error listing User-Agent block rules: ", err) return err diff --git a/cmd/flarectl/zone.go b/cmd/flarectl/zone.go index 1241ad8044c..929743ad68d 100644 --- a/cmd/flarectl/zone.go +++ b/cmd/flarectl/zone.go @@ -1,8 +1,10 @@ package main import ( + "context" "fmt" "os" + "strconv" "strings" cloudflare "github.com/cloudflare/cloudflare-go" @@ -38,7 +40,7 @@ func zoneCreate(c *cli.Context) error { zoneType = "full" } - _, err := api.CreateZone(zone, jumpstart, account, zoneType) + _, err := api.CreateZone(context.TODO(), zone, jumpstart, account, zoneType) if err != nil { fmt.Fprintln(os.Stderr, fmt.Sprintf("%s", err)) return err @@ -59,7 +61,7 @@ func zoneCheck(c *cli.Context) error { return err } - res, err := api.ZoneActivationCheck(zoneID) + res, err := api.ZoneActivationCheck(context.TODO(), zoneID) if err != nil { fmt.Println(err) return err @@ -70,7 +72,7 @@ func zoneCheck(c *cli.Context) error { } func zoneList(c *cli.Context) error { - zones, err := api.ListZones() + zones, err := api.ListZones(context.TODO()) if err != nil { fmt.Println(err) return err @@ -100,7 +102,7 @@ func zoneDelete(c *cli.Context) error { return err } - _, err = api.DeleteZone(zoneID) + _, err = api.DeleteZone(context.TODO(), zoneID) if err != nil { fmt.Fprintln(os.Stderr, fmt.Sprintf("%s", err)) return err @@ -139,7 +141,7 @@ func zoneCreateLockdown(c *cli.Context) error { var resp *cloudflare.ZoneLockdownResponse - resp, err = api.CreateZoneLockdown(zoneID, lockdown) + resp, err = api.CreateZoneLockdown(context.TODO(), zoneID, lockdown) if err != nil { fmt.Fprintln(os.Stderr, "Error creating ZONE lock down: ", err) return err @@ -162,7 +164,7 @@ func zoneInfo(c *cli.Context) error { cli.ShowSubcommandHelp(c) return nil } - zones, err := api.ListZones(zone) + zones, err := api.ListZones(context.TODO(), zone) if err != nil { fmt.Println(err) return err @@ -215,7 +217,7 @@ func zoneCachePurge(c *cli.Context) error { // Purge everything if c.Bool("everything") { - resp, err = api.PurgeEverything(zoneID) + resp, err = api.PurgeEverything(context.TODO(), zoneID) if err != nil { fmt.Fprintf(os.Stderr, "Error purging all from zone %q: %s\n", zoneName, err) return err @@ -239,7 +241,7 @@ func zoneCachePurge(c *cli.Context) error { Hosts: c.StringSlice("hosts"), } - resp, err = api.PurgeCache(zoneID, purgeReq) + resp, err = api.PurgeCache(context.TODO(), zoneID, purgeReq) if err != nil { fmt.Fprintf(os.Stderr, "Error purging the cache from zone %q: %s\n", zoneName, err) return err @@ -275,7 +277,7 @@ func zoneRecords(c *cli.Context) error { rr := cloudflare.DNSRecord{} var records []cloudflare.DNSRecord if c.String("id") != "" { - rec, err := api.DNSRecord(zoneID, c.String("id")) + rec, err := api.DNSRecord(context.TODO(), zoneID, c.String("id")) if err != nil { fmt.Println(err) return err @@ -292,7 +294,7 @@ func zoneRecords(c *cli.Context) error { rr.Name = c.String("content") } var err error - records, err = api.DNSRecords(zoneID, rr) + records, err = api.DNSRecords(context.TODO(), zoneID, rr) if err != nil { fmt.Println(err) return err @@ -316,7 +318,7 @@ func zoneRecords(c *cli.Context) error { r.Type, r.Name, r.Content, - fmt.Sprintf("%t", r.Proxied), + fmt.Sprintf("%s", strconv.FormatBool(*r.Proxied)), fmt.Sprintf("%d", r.TTL), }) } @@ -354,7 +356,7 @@ func zoneExport(c *cli.Context) error { return err } - res, err := api.ZoneExport(zoneID) + res, err := api.ZoneExport(context.TODO(), zoneID) if err != nil { fmt.Println(err) return err diff --git a/custom_hostname.go b/custom_hostname.go index fbd4350a00a..0e52919308f 100644 --- a/custom_hostname.go +++ b/custom_hostname.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" "time" @@ -113,12 +115,12 @@ type CustomHostnameFallbackOriginResponse struct { // hostname in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostnameSSL(zoneID string, customHostnameID string, ssl CustomHostnameSSL) (*CustomHostnameResponse, error) { +func (api *API) UpdateCustomHostnameSSL(ctx context.Context, zoneID string, customHostnameID string, ssl CustomHostnameSSL) (*CustomHostnameResponse, error) { uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID ch := CustomHostname{ SSL: ssl, } - res, err := api.makeRequest("PATCH", uri, ch) + res, err := api.makeRequestContext(ctx, "PATCH", uri, ch) if err != nil { return nil, err } @@ -135,9 +137,9 @@ func (api *API) UpdateCustomHostnameSSL(zoneID string, customHostnameID string, // hostname in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostname(zoneID string, customHostnameID string, ch CustomHostname) (*CustomHostnameResponse, error) { +func (api *API) UpdateCustomHostname(ctx context.Context, zoneID string, customHostnameID string, ch CustomHostname) (*CustomHostnameResponse, error) { uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("PATCH", uri, ch) + res, err := api.makeRequestContext(ctx, "PATCH", uri, ch) if err != nil { return nil, err } @@ -154,9 +156,9 @@ func (api *API) UpdateCustomHostname(zoneID string, customHostnameID string, ch // certificates). // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-delete-a-custom-hostname-and-any-issued-ssl-certificates- -func (api *API) DeleteCustomHostname(zoneID string, customHostnameID string) error { +func (api *API) DeleteCustomHostname(ctx context.Context, zoneID string, customHostnameID string) error { uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -173,9 +175,9 @@ func (api *API) DeleteCustomHostname(zoneID string, customHostnameID string) err // CreateCustomHostname creates a new custom hostname and requests that an SSL certificate be issued for it. // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-create-custom-hostname -func (api *API) CreateCustomHostname(zoneID string, ch CustomHostname) (*CustomHostnameResponse, error) { +func (api *API) CreateCustomHostname(ctx context.Context, zoneID string, ch CustomHostname) (*CustomHostnameResponse, error) { uri := "/zones/" + zoneID + "/custom_hostnames" - res, err := api.makeRequest("POST", uri, ch) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ch) if err != nil { return nil, err } @@ -195,7 +197,7 @@ func (api *API) CreateCustomHostname(zoneID string, ch CustomHostname) (*CustomH // The returned ResultInfo can be used to implement pagination. // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-list-custom-hostnames -func (api *API) CustomHostnames(zoneID string, page int, filter CustomHostname) ([]CustomHostname, ResultInfo, error) { +func (api *API) CustomHostnames(ctx context.Context, zoneID string, page int, filter CustomHostname) ([]CustomHostname, ResultInfo, error) { v := url.Values{} v.Set("per_page", "50") v.Set("page", strconv.Itoa(page)) @@ -205,7 +207,7 @@ func (api *API) CustomHostnames(zoneID string, page int, filter CustomHostname) query := "?" + v.Encode() uri := "/zones/" + zoneID + "/custom_hostnames" + query - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []CustomHostname{}, ResultInfo{}, err } @@ -221,9 +223,9 @@ func (api *API) CustomHostnames(zoneID string, page int, filter CustomHostname) // CustomHostname inspects the given custom hostname in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-custom-hostname-configuration-details -func (api *API) CustomHostname(zoneID string, customHostnameID string) (CustomHostname, error) { +func (api *API) CustomHostname(ctx context.Context, zoneID string, customHostnameID string) (CustomHostname, error) { uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return CustomHostname{}, err } @@ -238,8 +240,8 @@ func (api *API) CustomHostname(zoneID string, customHostnameID string) (CustomHo } // CustomHostnameIDByName retrieves the ID for the given hostname in the given zone. -func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) { - customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname}) +func (api *API) CustomHostnameIDByName(ctx context.Context, zoneID string, hostname string) (string, error) { + customHostnames, _, err := api.CustomHostnames(ctx, zoneID, 1, CustomHostname{Hostname: hostname}) if err != nil { return "", errors.Wrap(err, "CustomHostnames command failed") } @@ -254,9 +256,9 @@ func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, // UpdateCustomHostnameFallbackOrigin modifies the Custom Hostname Fallback origin in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-update-fallback-origin-for-custom-hostnames -func (api *API) UpdateCustomHostnameFallbackOrigin(zoneID string, chfo CustomHostnameFallbackOrigin) (*CustomHostnameFallbackOriginResponse, error) { +func (api *API) UpdateCustomHostnameFallbackOrigin(ctx context.Context, zoneID string, chfo CustomHostnameFallbackOrigin) (*CustomHostnameFallbackOriginResponse, error) { uri := "/zones/" + zoneID + "/custom_hostnames/fallback_origin" - res, err := api.makeRequest("PUT", uri, chfo) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, chfo) if err != nil { return nil, err } @@ -272,9 +274,9 @@ func (api *API) UpdateCustomHostnameFallbackOrigin(zoneID string, chfo CustomHos // DeleteCustomHostnameFallbackOrigin deletes the Custom Hostname Fallback origin in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-delete-fallback-origin-for-custom-hostnames -func (api *API) DeleteCustomHostnameFallbackOrigin(zoneID string) error { +func (api *API) DeleteCustomHostnameFallbackOrigin(ctx context.Context, zoneID string) error { uri := "/zones/" + zoneID + "/custom_hostnames/fallback_origin" - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -290,9 +292,9 @@ func (api *API) DeleteCustomHostnameFallbackOrigin(zoneID string) error { // CustomHostnameFallbackOrigin inspects the Custom Hostname Fallback origin in the given zone. // // API reference: https://api.cloudflare.com/#custom-hostname-fallback-origin-for-a-zone-properties -func (api *API) CustomHostnameFallbackOrigin(zoneID string) (CustomHostnameFallbackOrigin, error) { +func (api *API) CustomHostnameFallbackOrigin(ctx context.Context, zoneID string) (CustomHostnameFallbackOrigin, error) { uri := "/zones/" + zoneID + "/custom_hostnames/fallback_origin" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return CustomHostnameFallbackOrigin{}, err } diff --git a/custom_hostname_test.go b/custom_hostname_test.go index cd87abd1b8a..fa320708f91 100644 --- a/custom_hostname_test.go +++ b/custom_hostname_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -14,7 +15,7 @@ func TestCustomHostname_DeleteCustomHostname(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` @@ -23,7 +24,7 @@ func TestCustomHostname_DeleteCustomHostname(t *testing.T) { }`) }) - err := client.DeleteCustomHostname("foo", "bar") + err := client.DeleteCustomHostname(context.TODO(), "foo", "bar") assert.NoError(t, err) } @@ -33,7 +34,7 @@ func TestCustomHostname_CreateCustomHostname(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") w.WriteHeader(http.StatusCreated) @@ -74,7 +75,7 @@ func TestCustomHostname_CreateCustomHostname(t *testing.T) { }`) }) - response, err := client.CreateCustomHostname("foo", CustomHostname{Hostname: "app.example.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) + response, err := client.CreateCustomHostname(context.TODO(), "foo", CustomHostname{Hostname: "app.example.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) createdAt, _ := time.Parse(time.RFC3339, "2020-02-06T18:11:23.531995Z") @@ -119,7 +120,7 @@ func TestCustomHostname_CreateCustomHostname_CustomOrigin(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") w.WriteHeader(http.StatusCreated) @@ -146,7 +147,7 @@ func TestCustomHostname_CreateCustomHostname_CustomOrigin(t *testing.T) { }`) }) - response, err := client.CreateCustomHostname("foo", CustomHostname{Hostname: "app.example.com", CustomOriginServer: "example.app.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) + response, err := client.CreateCustomHostname(context.TODO(), "foo", CustomHostname{Hostname: "app.example.com", CustomOriginServer: "example.app.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) want := &CustomHostnameResponse{ Result: CustomHostname{ @@ -177,7 +178,7 @@ func TestCustomHostname_CustomHostnames(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -218,7 +219,7 @@ func TestCustomHostname_CustomHostnames(t *testing.T) { }`) }) - customHostnames, _, err := client.CustomHostnames("foo", 1, CustomHostname{}) + customHostnames, _, err := client.CustomHostnames(context.TODO(), "foo", 1, CustomHostname{}) want := []CustomHostname{ { @@ -255,7 +256,7 @@ func TestCustomHostname_CustomHostname(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -289,7 +290,7 @@ func TestCustomHostname_CustomHostname(t *testing.T) { }`) }) - customHostname, err := client.CustomHostname("foo", "bar") + customHostname, err := client.CustomHostname(context.TODO(), "foo", "bar") want := CustomHostname{ ID: "bar", @@ -325,7 +326,7 @@ func TestCustomHostname_CustomHostname_WithSSLError(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -355,7 +356,7 @@ func TestCustomHostname_CustomHostname_WithSSLError(t *testing.T) { }`) }) - customHostname, err := client.CustomHostname("foo", "bar") + customHostname, err := client.CustomHostname(context.TODO(), "foo", "bar") want := CustomHostname{ ID: "bar", @@ -367,7 +368,7 @@ func TestCustomHostname_CustomHostname_WithSSLError(t *testing.T) { CnameName: "810b7d5f01154524b961ba0cd578acc2.example.com", CnameTarget: "dcv.digicert.com", ValidationErrors: []CustomHostnameSSLValidationErrors{ - CustomHostnameSSLValidationErrors{ + { Message: "SERVFAIL looking up CAA for example.com", }, }, @@ -419,7 +420,7 @@ func TestCustomHostname_UpdateCustomHostnameSSL(t *testing.T) { }`) }) - response, err := client.UpdateCustomHostnameSSL("foo", "0d89c70d-ad9f-4843-b99f-6cc0252067e9", CustomHostnameSSL{Method: "cname", Type: "dv", Settings: CustomHostnameSSLSettings{HTTP2: "off", TLS13: "on"}}) + response, err := client.UpdateCustomHostnameSSL(context.TODO(), "foo", "0d89c70d-ad9f-4843-b99f-6cc0252067e9", CustomHostnameSSL{Method: "cname", Type: "dv", Settings: CustomHostnameSSLSettings{HTTP2: "off", TLS13: "on"}}) want := &CustomHostnameResponse{ Result: CustomHostname{ @@ -479,7 +480,7 @@ func TestCustomHostname_UpdateCustomHostname(t *testing.T) { }`) }) - response, err := client.UpdateCustomHostname("foo", "0d89c70d-ad9f-4843-b99f-6cc0252067e9", CustomHostname{Hostname: "app.example.com", CustomOriginServer: "example.app.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) + response, err := client.UpdateCustomHostname(context.TODO(), "foo", "0d89c70d-ad9f-4843-b99f-6cc0252067e9", CustomHostname{Hostname: "app.example.com", CustomOriginServer: "example.app.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv"}}) want := &CustomHostnameResponse{ Result: CustomHostname{ @@ -511,7 +512,7 @@ func TestCustomHostname_CustomHostnameFallbackOrigin(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/fallback_origin", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -530,7 +531,7 @@ func TestCustomHostname_CustomHostnameFallbackOrigin(t *testing.T) { }`) }) - customHostnameFallbackOrigin, err := client.CustomHostnameFallbackOrigin("foo") + customHostnameFallbackOrigin, err := client.CustomHostnameFallbackOrigin(context.TODO(), "foo") want := CustomHostnameFallbackOrigin{ Origin: "fallback.example.com", @@ -548,7 +549,7 @@ func TestCustomHostname_DeleteCustomHostnameFallbackOrigin(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/fallback_origin", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` @@ -557,7 +558,7 @@ func TestCustomHostname_DeleteCustomHostnameFallbackOrigin(t *testing.T) { }`) }) - err := client.DeleteCustomHostnameFallbackOrigin("foo") + err := client.DeleteCustomHostnameFallbackOrigin(context.TODO(), "foo") assert.NoError(t, err) } @@ -567,7 +568,7 @@ func TestCustomHostname_UpdateCustomHostnameFallbackOrigin(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames/fallback_origin", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") w.WriteHeader(http.StatusCreated) @@ -588,7 +589,7 @@ func TestCustomHostname_UpdateCustomHostnameFallbackOrigin(t *testing.T) { }`) }) - response, err := client.UpdateCustomHostnameFallbackOrigin("foo", CustomHostnameFallbackOrigin{Origin: "fallback.example.com"}) + response, err := client.UpdateCustomHostnameFallbackOrigin(context.TODO(), "foo", CustomHostnameFallbackOrigin{Origin: "fallback.example.com"}) want := &CustomHostnameFallbackOriginResponse{ Result: CustomHostnameFallbackOrigin{ @@ -609,7 +610,7 @@ func TestCustomHostname_CreateCustomHostnameCustomCertificateAuthority(t *testin defer teardown() mux.HandleFunc("/zones/foo/custom_hostnames", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") w.WriteHeader(http.StatusCreated) @@ -638,7 +639,7 @@ func TestCustomHostname_CreateCustomHostnameCustomCertificateAuthority(t *testin }`) }) - response, err := client.CreateCustomHostname("foo", CustomHostname{Hostname: "app.example.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv", CertificateAuthority: "lets_encrypt"}}) + response, err := client.CreateCustomHostname(context.TODO(), "foo", CustomHostname{Hostname: "app.example.com", SSL: CustomHostnameSSL{Method: "cname", Type: "dv", CertificateAuthority: "lets_encrypt"}}) createdAt, _ := time.Parse(time.RFC3339, "2020-06-30T21:37:36.563495Z") diff --git a/custom_pages.go b/custom_pages.go index e99faaff197..45fd504af17 100644 --- a/custom_pages.go +++ b/custom_pages.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -53,7 +55,7 @@ type CustomPageParameters struct { // // Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-list-available-custom-pages // Account API reference: https://api.cloudflare.com/#custom-pages-account--list-custom-pages -func (api *API) CustomPages(options *CustomPageOptions) ([]CustomPage, error) { +func (api *API) CustomPages(ctx context.Context, options *CustomPageOptions) ([]CustomPage, error) { var ( pageType, identifier string ) @@ -77,7 +79,7 @@ func (api *API) CustomPages(options *CustomPageOptions) ([]CustomPage, error) { uri := fmt.Sprintf("/%s/%s/custom_pages", pageType, identifier) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -95,7 +97,7 @@ func (api *API) CustomPages(options *CustomPageOptions) ([]CustomPage, error) { // // Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-custom-page-details // Account API reference: https://api.cloudflare.com/#custom-pages-account--custom-page-details -func (api *API) CustomPage(options *CustomPageOptions, customPageID string) (CustomPage, error) { +func (api *API) CustomPage(ctx context.Context, options *CustomPageOptions, customPageID string) (CustomPage, error) { var ( pageType, identifier string ) @@ -119,7 +121,7 @@ func (api *API) CustomPage(options *CustomPageOptions, customPageID string) (Cus uri := fmt.Sprintf("/%s/%s/custom_pages/%s", pageType, identifier, customPageID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return CustomPage{}, err } @@ -137,7 +139,7 @@ func (api *API) CustomPage(options *CustomPageOptions, customPageID string) (Cus // // Zone API reference: https://api.cloudflare.com/#custom-pages-for-a-zone-update-custom-page-url // Account API reference: https://api.cloudflare.com/#custom-pages-account--update-custom-page -func (api *API) UpdateCustomPage(options *CustomPageOptions, customPageID string, pageParameters CustomPageParameters) (CustomPage, error) { +func (api *API) UpdateCustomPage(ctx context.Context, options *CustomPageOptions, customPageID string, pageParameters CustomPageParameters) (CustomPage, error) { var ( pageType, identifier string ) @@ -161,7 +163,7 @@ func (api *API) UpdateCustomPage(options *CustomPageOptions, customPageID string uri := fmt.Sprintf("/%s/%s/custom_pages/%s", pageType, identifier, customPageID) - res, err := api.makeRequest("PUT", uri, pageParameters) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, pageParameters) if err != nil { return CustomPage{}, err } diff --git a/custom_pages_test.go b/custom_pages_test.go index bf383e3f317..81bc0a3b6c3 100644 --- a/custom_pages_test.go +++ b/custom_pages_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -42,12 +43,12 @@ var defaultCustomPage = CustomPage{ } func TestCustomPagesWithoutZoneIDOrAccountID(t *testing.T) { - _, err := client.CustomPages(&CustomPageOptions{}) + _, err := client.CustomPages(context.TODO(), &CustomPageOptions{}) assert.EqualError(t, err, "either account ID or zone ID must be provided") } func TestCustomPagesWithZoneIDAndAccountID(t *testing.T) { - _, err := client.CustomPages(&CustomPageOptions{ZoneID: "abc123", AccountID: "321cba"}) + _, err := client.CustomPages(context.TODO(), &CustomPageOptions{ZoneID: "abc123", AccountID: "321cba"}) assert.EqualError(t, err, "account ID and zone ID are mutually exclusive") } @@ -56,7 +57,7 @@ func TestCustomPagesForZone(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -90,7 +91,7 @@ func TestCustomPagesForZone(t *testing.T) { mux.HandleFunc("/zones/d992d6de698eaf2d8cf8fd53b89b18a4/custom_pages", handler) want := []CustomPage{expectedCustomPage} - pages, err := client.CustomPages(&CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}) + pages, err := client.CustomPages(context.TODO(), &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}) if assert.NoError(t, err) { assert.Equal(t, want, pages) @@ -102,7 +103,7 @@ func TestCustomPagesForAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -136,7 +137,7 @@ func TestCustomPagesForAccount(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/custom_pages", handler) want := []CustomPage{expectedCustomPage} - pages, err := client.CustomPages(&CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}) + pages, err := client.CustomPages(context.TODO(), &CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}) if assert.NoError(t, err) { assert.Equal(t, want, pages) @@ -148,7 +149,7 @@ func TestCustomPageForZone(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -179,7 +180,7 @@ func TestCustomPageForZone(t *testing.T) { mux.HandleFunc("/zones/d992d6de698eaf2d8cf8fd53b89b18a4/custom_pages/basic_challenge", handler) - page, err := client.CustomPage(&CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, "basic_challenge") + page, err := client.CustomPage(context.TODO(), &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, "basic_challenge") if assert.NoError(t, err) { assert.Equal(t, expectedCustomPage, page) @@ -191,7 +192,7 @@ func TestCustomPageForAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -222,7 +223,7 @@ func TestCustomPageForAccount(t *testing.T) { mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/custom_pages/basic_challenge", handler) - page, err := client.CustomPage(&CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}, "basic_challenge") + page, err := client.CustomPage(context.TODO(), &CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}, "basic_challenge") if assert.NoError(t, err) { assert.Equal(t, expectedCustomPage, page) @@ -234,7 +235,7 @@ func TestUpdateCustomPagesForAccount(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -264,11 +265,7 @@ func TestUpdateCustomPagesForAccount(t *testing.T) { } mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/custom_pages/basic_challenge", handler) - actual, err := client.UpdateCustomPage( - &CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}, - "basic_challenge", - CustomPageParameters{URL: "https://mytestexample.com", State: "customized"}, - ) + actual, err := client.UpdateCustomPage(context.TODO(), &CustomPageOptions{AccountID: "01a7362d577a6c3019a474fd6f485823"}, "basic_challenge", CustomPageParameters{URL: "https://mytestexample.com", State: "customized"}) if assert.NoError(t, err) { assert.Equal(t, updatedCustomPage, actual) @@ -280,7 +277,7 @@ func TestUpdateCustomPagesForZone(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -310,11 +307,7 @@ func TestUpdateCustomPagesForZone(t *testing.T) { } mux.HandleFunc("/zones/d992d6de698eaf2d8cf8fd53b89b18a4/custom_pages/basic_challenge", handler) - actual, err := client.UpdateCustomPage( - &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, - "basic_challenge", - CustomPageParameters{URL: "https://mytestexample.com", State: "customized"}, - ) + actual, err := client.UpdateCustomPage(context.TODO(), &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, "basic_challenge", CustomPageParameters{URL: "https://mytestexample.com", State: "customized"}) if assert.NoError(t, err) { assert.Equal(t, updatedCustomPage, actual) @@ -326,7 +319,7 @@ func TestUpdateCustomPagesToDefault(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, ` { @@ -350,11 +343,7 @@ func TestUpdateCustomPagesToDefault(t *testing.T) { } mux.HandleFunc("/zones/d992d6de698eaf2d8cf8fd53b89b18a4/custom_pages/basic_challenge", handler) - actual, err := client.UpdateCustomPage( - &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, - "basic_challenge", - CustomPageParameters{URL: nil, State: "default"}, - ) + actual, err := client.UpdateCustomPage(context.TODO(), &CustomPageOptions{ZoneID: "d992d6de698eaf2d8cf8fd53b89b18a4"}, "basic_challenge", CustomPageParameters{URL: nil, State: "default"}) if assert.NoError(t, err) { assert.Equal(t, defaultCustomPage, actual) diff --git a/diagnostics.go b/diagnostics.go index 53136d44be4..46b1f8fa97f 100644 --- a/diagnostics.go +++ b/diagnostics.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "encoding/json" "net/http" @@ -78,7 +79,7 @@ type DiagnosticsTracerouteResponseColos struct { // requested targets. // // API documentation: https://api.cloudflare.com/#diagnostics-traceroute -func (api *API) PerformTraceroute(accountID string, targets, colos []string, tracerouteOptions DiagnosticsTracerouteConfigurationOptions) ([]DiagnosticsTracerouteResponseResult, error) { +func (api *API) PerformTraceroute(ctx context.Context, accountID string, targets, colos []string, tracerouteOptions DiagnosticsTracerouteConfigurationOptions) ([]DiagnosticsTracerouteResponseResult, error) { uri := "/accounts/" + accountID + "/diagnostics/traceroute" diagnosticsPayload := DiagnosticsTracerouteConfiguration{ Targets: targets, @@ -86,7 +87,7 @@ func (api *API) PerformTraceroute(accountID string, targets, colos []string, tra Options: tracerouteOptions, } - res, err := api.makeRequest(http.MethodPost, uri, diagnosticsPayload) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, diagnosticsPayload) if err != nil { return []DiagnosticsTracerouteResponseResult{}, err } diff --git a/diagnostics_test.go b/diagnostics_test.go index 930da65ad20..4c63468aba5 100644 --- a/diagnostics_test.go +++ b/diagnostics_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "encoding/json" "fmt" "net/http" @@ -16,7 +17,7 @@ func TestDiagnosticsPerformTraceroute(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { var request DiagnosticsTracerouteConfiguration var err error - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) err = json.NewDecoder(r.Body).Decode(&request) assert.NoError(t, err) assert.Equal(t, request.Colos, []string{"den01"}, "Exepected key 'colos' to be [\"den01\"], got %+v", request.Colos) @@ -114,7 +115,7 @@ func TestDiagnosticsPerformTraceroute(t *testing.T) { } opts := DiagnosticsTracerouteConfigurationOptions{PacketsPerTTL: 1, PacketType: "imcp", MaxTTL: 1, WaitTime: 1} - trace, err := client.PerformTraceroute("01a7362d577a6c3019a474fd6f485823", []string{"1.1.1.1"}, []string{"den01"}, opts) + trace, err := client.PerformTraceroute(context.TODO(), "01a7362d577a6c3019a474fd6f485823", []string{"1.1.1.1"}, []string{"den01"}, opts) if assert.NoError(t, err) { assert.Equal(t, want, trace) @@ -128,7 +129,7 @@ func TestDiagnosticsPerformTracerouteEmptyColos(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { var request DiagnosticsTracerouteConfiguration var err error - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) err = json.NewDecoder(r.Body).Decode(&request) assert.NoError(t, err) assert.Nil(t, request.Colos, "Exepected key 'colos' to be nil, got %+v", request.Colos) @@ -226,7 +227,7 @@ func TestDiagnosticsPerformTracerouteEmptyColos(t *testing.T) { } opts := DiagnosticsTracerouteConfigurationOptions{PacketsPerTTL: 1, PacketType: "imcp", MaxTTL: 1, WaitTime: 1} - trace, err := client.PerformTraceroute("01a7362d577a6c3019a474fd6f485823", []string{"1.1.1.1"}, []string{}, opts) + trace, err := client.PerformTraceroute(context.TODO(), "01a7362d577a6c3019a474fd6f485823", []string{"1.1.1.1"}, []string{}, opts) if assert.NoError(t, err) { assert.Equal(t, want, trace) diff --git a/dns.go b/dns.go index 51ca39a9a96..d97e64f9c35 100644 --- a/dns.go +++ b/dns.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" "time" @@ -16,7 +18,7 @@ type DNSRecord struct { Name string `json:"name,omitempty"` Content string `json:"content,omitempty"` Proxiable bool `json:"proxiable,omitempty"` - Proxied bool `json:"proxied,omitempty"` + Proxied *bool `json:"proxied,omitempty"` TTL int `json:"ttl,omitempty"` Locked bool `json:"locked,omitempty"` ZoneID string `json:"zone_id,omitempty"` @@ -25,7 +27,7 @@ type DNSRecord struct { ModifiedOn time.Time `json:"modified_on,omitempty"` Data interface{} `json:"data,omitempty"` // data returned by: SRV, LOC Meta interface{} `json:"meta,omitempty"` - Priority int `json:"priority,omitempty"` + Priority *uint16 `json:"priority,omitempty"` } // DNSRecordResponse represents the response from the DNS endpoint. @@ -45,9 +47,9 @@ type DNSListResponse struct { // CreateDNSRecord creates a DNS record for the zone identifier. // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record -func (api *API) CreateDNSRecord(zoneID string, rr DNSRecord) (*DNSRecordResponse, error) { +func (api *API) CreateDNSRecord(ctx context.Context, zoneID string, rr DNSRecord) (*DNSRecordResponse, error) { uri := "/zones/" + zoneID + "/dns_records" - res, err := api.makeRequest("POST", uri, rr) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rr) if err != nil { return nil, err } @@ -66,7 +68,7 @@ func (api *API) CreateDNSRecord(zoneID string, rr DNSRecord) (*DNSRecordResponse // This takes a DNSRecord to allow filtering of the results returned. // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records -func (api *API) DNSRecords(zoneID string, rr DNSRecord) ([]DNSRecord, error) { +func (api *API) DNSRecords(ctx context.Context, zoneID string, rr DNSRecord) ([]DNSRecord, error) { // Construct a query string v := url.Values{} // Request as many records as possible per page - API max is 100 @@ -90,7 +92,7 @@ func (api *API) DNSRecords(zoneID string, rr DNSRecord) ([]DNSRecord, error) { v.Set("page", strconv.Itoa(page)) query = "?" + v.Encode() uri := "/zones/" + zoneID + "/dns_records" + query - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []DNSRecord{}, err } @@ -113,9 +115,9 @@ func (api *API) DNSRecords(zoneID string, rr DNSRecord) ([]DNSRecord, error) { // identifiers. // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details -func (api *API) DNSRecord(zoneID, recordID string) (DNSRecord, error) { +func (api *API) DNSRecord(ctx context.Context, zoneID, recordID string) (DNSRecord, error) { uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return DNSRecord{}, err } @@ -131,8 +133,8 @@ func (api *API) DNSRecord(zoneID, recordID string) (DNSRecord, error) { // identifiers. // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record -func (api *API) UpdateDNSRecord(zoneID, recordID string, rr DNSRecord) error { - rec, err := api.DNSRecord(zoneID, recordID) +func (api *API) UpdateDNSRecord(ctx context.Context, zoneID, recordID string, rr DNSRecord) error { + rec, err := api.DNSRecord(ctx, zoneID, recordID) if err != nil { return err } @@ -145,7 +147,7 @@ func (api *API) UpdateDNSRecord(zoneID, recordID string, rr DNSRecord) error { rr.Type = rec.Type } uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("PATCH", uri, rr) + res, err := api.makeRequestContext(ctx, "PATCH", uri, rr) if err != nil { return err } @@ -161,9 +163,9 @@ func (api *API) UpdateDNSRecord(zoneID, recordID string, rr DNSRecord) error { // identifiers. // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record -func (api *API) DeleteDNSRecord(zoneID, recordID string) error { +func (api *API) DeleteDNSRecord(ctx context.Context, zoneID, recordID string) error { uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/dns_example_test.go b/dns_example_test.go index d01b8b51608..2a4277b84c0 100644 --- a/dns_example_test.go +++ b/dns_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -19,7 +20,7 @@ func ExampleAPI_DNSRecords_all() { } // Fetch all records for a zone - recs, err := api.DNSRecords(zoneID, cloudflare.DNSRecord{}) + recs, err := api.DNSRecords(context.TODO(), zoneID, cloudflare.DNSRecord{}) if err != nil { log.Fatal(err) } @@ -42,7 +43,7 @@ func ExampleAPI_DNSRecords_filterByContent() { // Fetch only records whose content is 127.0.0.1 localhost := cloudflare.DNSRecord{Content: "127.0.0.1"} - recs, err := api.DNSRecords(zoneID, localhost) + recs, err := api.DNSRecords(context.TODO(), zoneID, localhost) if err != nil { log.Fatal(err) } @@ -66,7 +67,7 @@ func ExampleAPI_DNSRecords_filterByName() { // Fetch records of any type with name "foo.example.com" // The name must be fully-qualified foo := cloudflare.DNSRecord{Name: "foo.example.com"} - recs, err := api.DNSRecords(zoneID, foo) + recs, err := api.DNSRecords(context.TODO(), zoneID, foo) if err != nil { log.Fatal(err) } @@ -89,7 +90,7 @@ func ExampleAPI_DNSRecords_filterByType() { // Fetch only AAAA type records aaaa := cloudflare.DNSRecord{Type: "AAAA"} - recs, err := api.DNSRecords(zoneID, aaaa) + recs, err := api.DNSRecords(context.TODO(), zoneID, aaaa) if err != nil { log.Fatal(err) } diff --git a/example_test.go b/example_test.go index 74ec970a8b8..0749c62cbe1 100644 --- a/example_test.go +++ b/example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" cloudflare "github.com/cloudflare/cloudflare-go" @@ -27,7 +28,7 @@ func Example() { } // Fetch all DNS records for example.org - records, err := api.DNSRecords(zoneID, cloudflare.DNSRecord{}) + records, err := api.DNSRecords(context.TODO(), zoneID, cloudflare.DNSRecord{}) if err != nil { fmt.Println(err) return diff --git a/filter.go b/filter.go index 98d2acd7d07..1f3fa545908 100644 --- a/filter.go +++ b/filter.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "strings" @@ -61,10 +63,10 @@ type FilterValidationExpressionMessage struct { // Filter returns a single filter in a zone based on the filter ID. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/get/#get-by-filter-id -func (api *API) Filter(zoneID, filterID string) (Filter, error) { +func (api *API) Filter(ctx context.Context, zoneID, filterID string) (Filter, error) { uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filterID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return Filter{}, err } @@ -81,7 +83,7 @@ func (api *API) Filter(zoneID, filterID string) (Filter, error) { // Filters returns all filters for a zone. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/get/#get-all-filters -func (api *API) Filters(zoneID string, pageOpts PaginationOptions) ([]Filter, error) { +func (api *API) Filters(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]Filter, error) { uri := "/zones/" + zoneID + "/filters" v := url.Values{} @@ -97,7 +99,7 @@ func (api *API) Filters(zoneID string, pageOpts PaginationOptions) ([]Filter, er uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []Filter{}, err } @@ -114,10 +116,10 @@ func (api *API) Filters(zoneID string, pageOpts PaginationOptions) ([]Filter, er // CreateFilters creates new filters. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/post/ -func (api *API) CreateFilters(zoneID string, filters []Filter) ([]Filter, error) { +func (api *API) CreateFilters(ctx context.Context, zoneID string, filters []Filter) ([]Filter, error) { uri := "/zones/" + zoneID + "/filters" - res, err := api.makeRequest("POST", uri, filters) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, filters) if err != nil { return []Filter{}, err } @@ -134,14 +136,14 @@ func (api *API) CreateFilters(zoneID string, filters []Filter) ([]Filter, error) // UpdateFilter updates a single filter. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/put/#update-a-single-filter -func (api *API) UpdateFilter(zoneID string, filter Filter) (Filter, error) { +func (api *API) UpdateFilter(ctx context.Context, zoneID string, filter Filter) (Filter, error) { if filter.ID == "" { return Filter{}, errors.Errorf("filter ID cannot be empty") } uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filter.ID) - res, err := api.makeRequest("PUT", uri, filter) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, filter) if err != nil { return Filter{}, err } @@ -158,7 +160,7 @@ func (api *API) UpdateFilter(zoneID string, filter Filter) (Filter, error) { // UpdateFilters updates many filters at once. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/put/#update-multiple-filters -func (api *API) UpdateFilters(zoneID string, filters []Filter) ([]Filter, error) { +func (api *API) UpdateFilters(ctx context.Context, zoneID string, filters []Filter) ([]Filter, error) { for _, filter := range filters { if filter.ID == "" { return []Filter{}, errors.Errorf("filter ID cannot be empty") @@ -167,7 +169,7 @@ func (api *API) UpdateFilters(zoneID string, filters []Filter) ([]Filter, error) uri := "/zones/" + zoneID + "/filters" - res, err := api.makeRequest("PUT", uri, filters) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, filters) if err != nil { return []Filter{}, err } @@ -184,14 +186,14 @@ func (api *API) UpdateFilters(zoneID string, filters []Filter) ([]Filter, error) // DeleteFilter deletes a single filter. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/delete/#delete-a-single-filter -func (api *API) DeleteFilter(zoneID, filterID string) error { +func (api *API) DeleteFilter(ctx context.Context, zoneID, filterID string) error { if filterID == "" { return errors.Errorf("filter ID cannot be empty") } uri := fmt.Sprintf("/zones/%s/filters/%s", zoneID, filterID) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -202,11 +204,11 @@ func (api *API) DeleteFilter(zoneID, filterID string) error { // DeleteFilters deletes multiple filters. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/delete/#delete-multiple-filters -func (api *API) DeleteFilters(zoneID string, filterIDs []string) error { +func (api *API) DeleteFilters(ctx context.Context, zoneID string, filterIDs []string) error { ids := strings.Join(filterIDs, ",") uri := fmt.Sprintf("/zones/%s/filters?id=%s", zoneID, ids) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -217,11 +219,11 @@ func (api *API) DeleteFilters(zoneID string, filterIDs []string) error { // ValidateFilterExpression checks correctness of a filter expression. // // API reference: https://developers.cloudflare.com/firewall/api/cf-filters/validation/ -func (api *API) ValidateFilterExpression(expression string) error { +func (api *API) ValidateFilterExpression(ctx context.Context, expression string) error { uri := fmt.Sprintf("/filters/validate-expr") expressionPayload := FilterValidateExpression{Expression: expression} - _, err := api.makeRequest("POST", uri, expressionPayload) + _, err := api.makeRequestContext(ctx, http.MethodPost, uri, expressionPayload) if err != nil { var filterValidationResponse FilterValidateExpressionResponse diff --git a/filter_test.go b/filter_test.go index b7cdd5cb995..acf12848c21 100644 --- a/filter_test.go +++ b/filter_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -18,7 +19,7 @@ func TestFilter(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -42,7 +43,7 @@ func TestFilter(t *testing.T) { Expression: "ip.src eq 127.0.0.1", } - actual, err := client.Filter("d56084adb405e0b7e32c52321bf07be6", "b7ff25282d394be7b945e23c7106ce8a") + actual, err := client.Filter(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "b7ff25282d394be7b945e23c7106ce8a") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -54,7 +55,7 @@ func TestFilters(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -130,7 +131,7 @@ func TestFilters(t *testing.T) { }, } - actual, err := client.Filters("d56084adb405e0b7e32c52321bf07be6", pageOpts) + actual, err := client.Filters(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", pageOpts) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -142,7 +143,7 @@ func TestCreateSingleFilter(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -170,7 +171,7 @@ func TestCreateSingleFilter(t *testing.T) { }, } - actual, err := client.CreateFilters("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.CreateFilters(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -182,7 +183,7 @@ func TestCreateMultipleFilters(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -222,7 +223,7 @@ func TestCreateMultipleFilters(t *testing.T) { }, } - actual, err := client.CreateFilters("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.CreateFilters(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -234,7 +235,7 @@ func TestUpdateSingleFilter(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -258,7 +259,7 @@ func TestUpdateSingleFilter(t *testing.T) { Expression: "ip.src eq 93.184.216.0", } - actual, err := client.UpdateFilter("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.UpdateFilter(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -270,7 +271,7 @@ func TestUpdateMultipleFilters(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -310,7 +311,7 @@ func TestUpdateMultipleFilters(t *testing.T) { }, } - actual, err := client.UpdateFilters("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.UpdateFilters(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -322,7 +323,7 @@ func TestDeleteFilter(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [], @@ -335,7 +336,7 @@ func TestDeleteFilter(t *testing.T) { mux.HandleFunc("/zones/d56084adb405e0b7e32c52321bf07be6/filters/60ee852f9cbb4802978d15600c7f3110", handler) - err := client.DeleteFilter("d56084adb405e0b7e32c52321bf07be6", "60ee852f9cbb4802978d15600c7f3110") + err := client.DeleteFilter(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "60ee852f9cbb4802978d15600c7f3110") assert.Nil(t, err) assert.NoError(t, err) } @@ -344,6 +345,6 @@ func TestDeleteFilterWithMissingID(t *testing.T) { setup() defer teardown() - err := client.DeleteFilter("d56084adb405e0b7e32c52321bf07be6", "") + err := client.DeleteFilter(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "") assert.EqualError(t, err, "filter ID cannot be empty") } diff --git a/firewall.go b/firewall.go index 1bf6918774e..6700bdedd4e 100644 --- a/firewall.go +++ b/firewall.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" "time" @@ -57,38 +59,38 @@ type AccessRuleListResponse struct { // This takes an AccessRule to allow filtering of the results returned. // // API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) ListUserAccessRules(accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/user", accessRule, page) +func (api *API) ListUserAccessRules(ctx context.Context, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { + return api.listAccessRules(ctx, "/user", accessRule, page) } // CreateUserAccessRule creates a firewall access rule for the logged-in user. // // API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-create-access-rule -func (api *API) CreateUserAccessRule(accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/user", accessRule) +func (api *API) CreateUserAccessRule(ctx context.Context, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.createAccessRule(ctx, "/user", accessRule) } // UserAccessRule returns the details of a user's account access rule. // // API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) UserAccessRule(accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule("/user", accessRuleID) +func (api *API) UserAccessRule(ctx context.Context, accessRuleID string) (*AccessRuleResponse, error) { + return api.retrieveAccessRule(ctx, "/user", accessRuleID) } // UpdateUserAccessRule updates a single access rule for the logged-in user & // given access rule identifier. // // API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) UpdateUserAccessRule(accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/user", accessRuleID, accessRule) +func (api *API) UpdateUserAccessRule(ctx context.Context, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.updateAccessRule(ctx, "/user", accessRuleID, accessRule) } // DeleteUserAccessRule deletes a single access rule for the logged-in user and // access rule identifiers. // // API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) DeleteUserAccessRule(accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/user", accessRuleID) +func (api *API) DeleteUserAccessRule(ctx context.Context, accessRuleID string) (*AccessRuleResponse, error) { + return api.deleteAccessRule(ctx, "/user", accessRuleID) } // ListZoneAccessRules returns a slice of access rules for the given zone @@ -97,39 +99,39 @@ func (api *API) DeleteUserAccessRule(accessRuleID string) (*AccessRuleResponse, // This takes an AccessRule to allow filtering of the results returned. // // API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ListZoneAccessRules(zoneID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/zones/"+zoneID, accessRule, page) +func (api *API) ListZoneAccessRules(ctx context.Context, zoneID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { + return api.listAccessRules(ctx, "/zones/"+zoneID, accessRule, page) } // CreateZoneAccessRule creates a firewall access rule for the given zone // identifier. // // API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-create-access-rule -func (api *API) CreateZoneAccessRule(zoneID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/zones/"+zoneID, accessRule) +func (api *API) CreateZoneAccessRule(ctx context.Context, zoneID string, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.createAccessRule(ctx, "/zones/"+zoneID, accessRule) } // ZoneAccessRule returns the details of a zone's access rule. // // API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ZoneAccessRule(zoneID string, accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule("/zones/"+zoneID, accessRuleID) +func (api *API) ZoneAccessRule(ctx context.Context, zoneID string, accessRuleID string) (*AccessRuleResponse, error) { + return api.retrieveAccessRule(ctx, "/zones/"+zoneID, accessRuleID) } // UpdateZoneAccessRule updates a single access rule for the given zone & // access rule identifiers. // // API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-update-access-rule -func (api *API) UpdateZoneAccessRule(zoneID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/zones/"+zoneID, accessRuleID, accessRule) +func (api *API) UpdateZoneAccessRule(ctx context.Context, zoneID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.updateAccessRule(ctx, "/zones/"+zoneID, accessRuleID, accessRule) } // DeleteZoneAccessRule deletes a single access rule for the given zone and // access rule identifiers. // // API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-delete-access-rule -func (api *API) DeleteZoneAccessRule(zoneID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/zones/"+zoneID, accessRuleID) +func (api *API) DeleteZoneAccessRule(ctx context.Context, zoneID, accessRuleID string) (*AccessRuleResponse, error) { + return api.deleteAccessRule(ctx, "/zones/"+zoneID, accessRuleID) } // ListAccountAccessRules returns a slice of access rules for the given @@ -138,42 +140,42 @@ func (api *API) DeleteZoneAccessRule(zoneID, accessRuleID string) (*AccessRuleRe // This takes an AccessRule to allow filtering of the results returned. // // API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-list-access-rules -func (api *API) ListAccountAccessRules(accountID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/accounts/"+accountID, accessRule, page) +func (api *API) ListAccountAccessRules(ctx context.Context, accountID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { + return api.listAccessRules(ctx, "/accounts/"+accountID, accessRule, page) } // CreateAccountAccessRule creates a firewall access rule for the given // account identifier. // // API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-create-access-rule -func (api *API) CreateAccountAccessRule(accountID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/accounts/"+accountID, accessRule) +func (api *API) CreateAccountAccessRule(ctx context.Context, accountID string, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.createAccessRule(ctx, "/accounts/"+accountID, accessRule) } // AccountAccessRule returns the details of an account's access rule. // // API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-access-rule-details -func (api *API) AccountAccessRule(accountID string, accessRuleID string) (*AccessRuleResponse, error) { - return api.retrieveAccessRule("/accounts/"+accountID, accessRuleID) +func (api *API) AccountAccessRule(ctx context.Context, accountID string, accessRuleID string) (*AccessRuleResponse, error) { + return api.retrieveAccessRule(ctx, "/accounts/"+accountID, accessRuleID) } // UpdateAccountAccessRule updates a single access rule for the given // account & access rule identifiers. // // API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-update-access-rule -func (api *API) UpdateAccountAccessRule(accountID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/accounts/"+accountID, accessRuleID, accessRule) +func (api *API) UpdateAccountAccessRule(ctx context.Context, accountID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { + return api.updateAccessRule(ctx, "/accounts/"+accountID, accessRuleID, accessRule) } // DeleteAccountAccessRule deletes a single access rule for the given // account and access rule identifiers. // // API reference: https://api.cloudflare.com/#account-level-firewall-access-rule-delete-access-rule -func (api *API) DeleteAccountAccessRule(accountID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/accounts/"+accountID, accessRuleID) +func (api *API) DeleteAccountAccessRule(ctx context.Context, accountID, accessRuleID string) (*AccessRuleResponse, error) { + return api.deleteAccessRule(ctx, "/accounts/"+accountID, accessRuleID) } -func (api *API) listAccessRules(prefix string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { +func (api *API) listAccessRules(ctx context.Context, prefix string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { // Construct a query string v := url.Values{} if page <= 0 { @@ -201,7 +203,7 @@ func (api *API) listAccessRules(prefix string, accessRule AccessRule, page int) query := "?" + v.Encode() uri := prefix + "/firewall/access_rules/rules" + query - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -214,9 +216,9 @@ func (api *API) listAccessRules(prefix string, accessRule AccessRule, page int) return response, nil } -func (api *API) createAccessRule(prefix string, accessRule AccessRule) (*AccessRuleResponse, error) { +func (api *API) createAccessRule(ctx context.Context, prefix string, accessRule AccessRule) (*AccessRuleResponse, error) { uri := prefix + "/firewall/access_rules/rules" - res, err := api.makeRequest("POST", uri, accessRule) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, accessRule) if err != nil { return nil, err } @@ -230,10 +232,10 @@ func (api *API) createAccessRule(prefix string, accessRule AccessRule) (*AccessR return response, nil } -func (api *API) retrieveAccessRule(prefix, accessRuleID string) (*AccessRuleResponse, error) { +func (api *API) retrieveAccessRule(ctx context.Context, prefix, accessRuleID string) (*AccessRuleResponse, error) { uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err @@ -248,9 +250,9 @@ func (api *API) retrieveAccessRule(prefix, accessRuleID string) (*AccessRuleResp return response, nil } -func (api *API) updateAccessRule(prefix, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { +func (api *API) updateAccessRule(ctx context.Context, prefix, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("PATCH", uri, accessRule) + res, err := api.makeRequestContext(ctx, "PATCH", uri, accessRule) if err != nil { return nil, err } @@ -263,9 +265,9 @@ func (api *API) updateAccessRule(prefix, accessRuleID string, accessRule AccessR return response, nil } -func (api *API) deleteAccessRule(prefix, accessRuleID string) (*AccessRuleResponse, error) { +func (api *API) deleteAccessRule(ctx context.Context, prefix, accessRuleID string) (*AccessRuleResponse, error) { uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return nil, err } diff --git a/firewall_example_test.go b/firewall_example_test.go index 6218fb2253a..47d12f7faf9 100644 --- a/firewall_example_test.go +++ b/firewall_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -19,7 +20,7 @@ func ExampleAPI_ListZoneAccessRules_all() { } // Fetch all access rules for a zone - response, err := api.ListZoneAccessRules(zoneID, cloudflare.AccessRule{}, 1) + response, err := api.ListZoneAccessRules(context.TODO(), zoneID, cloudflare.AccessRule{}, 1) if err != nil { log.Fatal(err) } @@ -44,7 +45,7 @@ func ExampleAPI_ListZoneAccessRules_filterByIP() { localhost := cloudflare.AccessRule{ Configuration: cloudflare.AccessRuleConfiguration{Target: "127.0.0.1"}, } - response, err := api.ListZoneAccessRules(zoneID, localhost, 1) + response, err := api.ListZoneAccessRules(context.TODO(), zoneID, localhost, 1) if err != nil { log.Fatal(err) } @@ -69,7 +70,7 @@ func ExampleAPI_ListZoneAccessRules_filterByMode() { foo := cloudflare.AccessRule{ Mode: "block", } - response, err := api.ListZoneAccessRules(zoneID, foo, 1) + response, err := api.ListZoneAccessRules(context.TODO(), zoneID, foo, 1) if err != nil { log.Fatal(err) } @@ -94,7 +95,7 @@ func ExampleAPI_ListZoneAccessRules_filterByNote() { foo := cloudflare.AccessRule{ Notes: "example", } - response, err := api.ListZoneAccessRules(zoneID, foo, 1) + response, err := api.ListZoneAccessRules(context.TODO(), zoneID, foo, 1) if err != nil { log.Fatal(err) } diff --git a/firewall_rules.go b/firewall_rules.go index 3bfac0f2f5d..349f8b57e02 100644 --- a/firewall_rules.go +++ b/firewall_rules.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "time" @@ -42,7 +44,7 @@ type FirewallRuleResponse struct { // FirewallRules returns all firewall rules. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/get/#get-all-rules -func (api *API) FirewallRules(zoneID string, pageOpts PaginationOptions) ([]FirewallRule, error) { +func (api *API) FirewallRules(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]FirewallRule, error) { uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) v := url.Values{} @@ -58,7 +60,7 @@ func (api *API) FirewallRules(zoneID string, pageOpts PaginationOptions) ([]Fire uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []FirewallRule{}, err } @@ -75,10 +77,10 @@ func (api *API) FirewallRules(zoneID string, pageOpts PaginationOptions) ([]Fire // FirewallRule returns a single firewall rule based on the ID. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/get/#get-by-rule-id -func (api *API) FirewallRule(zoneID, firewallRuleID string) (FirewallRule, error) { +func (api *API) FirewallRule(ctx context.Context, zoneID, firewallRuleID string) (FirewallRule, error) { uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRuleID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return FirewallRule{}, err } @@ -95,10 +97,10 @@ func (api *API) FirewallRule(zoneID, firewallRuleID string) (FirewallRule, error // CreateFirewallRules creates new firewall rules. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/post/ -func (api *API) CreateFirewallRules(zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { +func (api *API) CreateFirewallRules(ctx context.Context, zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) - res, err := api.makeRequest("POST", uri, firewallRules) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, firewallRules) if err != nil { return []FirewallRule{}, err } @@ -115,14 +117,14 @@ func (api *API) CreateFirewallRules(zoneID string, firewallRules []FirewallRule) // UpdateFirewallRule updates a single firewall rule. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/put/#update-a-single-rule -func (api *API) UpdateFirewallRule(zoneID string, firewallRule FirewallRule) (FirewallRule, error) { +func (api *API) UpdateFirewallRule(ctx context.Context, zoneID string, firewallRule FirewallRule) (FirewallRule, error) { if firewallRule.ID == "" { return FirewallRule{}, errors.Errorf("firewall rule ID cannot be empty") } uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRule.ID) - res, err := api.makeRequest("PUT", uri, firewallRule) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, firewallRule) if err != nil { return FirewallRule{}, err } @@ -139,7 +141,7 @@ func (api *API) UpdateFirewallRule(zoneID string, firewallRule FirewallRule) (Fi // UpdateFirewallRules updates a single firewall rule. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/put/#update-multiple-rules -func (api *API) UpdateFirewallRules(zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { +func (api *API) UpdateFirewallRules(ctx context.Context, zoneID string, firewallRules []FirewallRule) ([]FirewallRule, error) { for _, firewallRule := range firewallRules { if firewallRule.ID == "" { return []FirewallRule{}, errors.Errorf("firewall ID cannot be empty") @@ -148,7 +150,7 @@ func (api *API) UpdateFirewallRules(zoneID string, firewallRules []FirewallRule) uri := fmt.Sprintf("/zones/%s/firewall/rules", zoneID) - res, err := api.makeRequest("PUT", uri, firewallRules) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, firewallRules) if err != nil { return []FirewallRule{}, err } @@ -165,14 +167,14 @@ func (api *API) UpdateFirewallRules(zoneID string, firewallRules []FirewallRule) // DeleteFirewallRule deletes a single firewall rule. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/delete/#delete-a-single-rule -func (api *API) DeleteFirewallRule(zoneID, firewallRuleID string) error { +func (api *API) DeleteFirewallRule(ctx context.Context, zoneID, firewallRuleID string) error { if firewallRuleID == "" { return errors.Errorf("firewall rule ID cannot be empty") } uri := fmt.Sprintf("/zones/%s/firewall/rules/%s", zoneID, firewallRuleID) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -183,7 +185,7 @@ func (api *API) DeleteFirewallRule(zoneID, firewallRuleID string) error { // DeleteFirewallRules deletes multiple firewall rules at once. // // API reference: https://developers.cloudflare.com/firewall/api/cf-firewall-rules/delete/#delete-multiple-rules -func (api *API) DeleteFirewallRules(zoneID string, firewallRuleIDs []string) error { +func (api *API) DeleteFirewallRules(ctx context.Context, zoneID string, firewallRuleIDs []string) error { v := url.Values{} for _, ruleID := range firewallRuleIDs { @@ -192,7 +194,7 @@ func (api *API) DeleteFirewallRules(zoneID string, firewallRuleIDs []string) err uri := fmt.Sprintf("/zones/%s/firewall/rules?%s", zoneID, v.Encode()) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/firewall_rules_test.go b/firewall_rules_test.go index 436ee1d6a1f..4610e204cc8 100644 --- a/firewall_rules_test.go +++ b/firewall_rules_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -18,7 +19,7 @@ func TestFirewallRules(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":[ @@ -172,7 +173,7 @@ func TestFirewallRules(t *testing.T) { }, } - actual, err := client.FirewallRules("d56084adb405e0b7e32c52321bf07be6", firewallRulePageOpts) + actual, err := client.FirewallRules(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", firewallRulePageOpts) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -184,7 +185,7 @@ func TestFirewallRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":{ @@ -222,7 +223,7 @@ func TestFirewallRule(t *testing.T) { }, } - actual, err := client.FirewallRule("d56084adb405e0b7e32c52321bf07be6", "f2d427378e7542acb295380d352e2ebd") + actual, err := client.FirewallRule(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "f2d427378e7542acb295380d352e2ebd") if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -234,7 +235,7 @@ func TestCreateSingleFirewallRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":[ @@ -276,7 +277,7 @@ func TestCreateSingleFirewallRule(t *testing.T) { }, } - actual, err := client.CreateFirewallRules("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.CreateFirewallRules(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -288,7 +289,7 @@ func TestCreateMultipleFirewallRules(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":[ @@ -356,7 +357,7 @@ func TestCreateMultipleFirewallRules(t *testing.T) { }, } - actual, err := client.CreateFirewallRules("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.CreateFirewallRules(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -381,7 +382,7 @@ func TestUpdateFirewallRuleWithMissingID(t *testing.T) { }, } - _, err := client.UpdateFirewallRule("d56084adb405e0b7e32c52321bf07be6", want) + _, err := client.UpdateFirewallRule(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) assert.EqualError(t, err, "firewall rule ID cannot be empty") } @@ -390,7 +391,7 @@ func TestUpdateSingleFirewallRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":{ @@ -428,7 +429,7 @@ func TestUpdateSingleFirewallRule(t *testing.T) { }, } - actual, err := client.UpdateFirewallRule("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.UpdateFirewallRule(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -440,7 +441,7 @@ func TestUpdateMultipleFirewallRules(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result":[ @@ -508,7 +509,7 @@ func TestUpdateMultipleFirewallRules(t *testing.T) { }, } - actual, err := client.UpdateFirewallRules("d56084adb405e0b7e32c52321bf07be6", want) + actual, err := client.UpdateFirewallRules(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) @@ -520,7 +521,7 @@ func TestDeleteSingleFirewallRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [], @@ -533,7 +534,7 @@ func TestDeleteSingleFirewallRule(t *testing.T) { mux.HandleFunc("/zones/d56084adb405e0b7e32c52321bf07be6/firewall/rules/f2d427378e7542acb295380d352e2ebd", handler) - err := client.DeleteFirewallRule("d56084adb405e0b7e32c52321bf07be6", "f2d427378e7542acb295380d352e2ebd") + err := client.DeleteFirewallRule(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "f2d427378e7542acb295380d352e2ebd") assert.NoError(t, err) } @@ -541,6 +542,6 @@ func TestDeleteFirewallRuleWithMissingID(t *testing.T) { setup() defer teardown() - err := client.DeleteFirewallRule("d56084adb405e0b7e32c52321bf07be6", "") + err := client.DeleteFirewallRule(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", "") assert.EqualError(t, err, "firewall rule ID cannot be empty") } diff --git a/go.mod b/go.mod index 4723246811e..52f0508b7bb 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,17 @@ module github.com/cloudflare/cloudflare-go go 1.14 require ( + cloud.google.com/go/storage v1.13.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/olekukonko/tablewriter v0.0.5 github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.7.0 github.com/urfave/cli/v2 v2.3.0 - golang.org/x/net v0.0.0-20210119194325-5f4716e94777 + github.com/yuin/goldmark v1.3.2 // indirect + golang.org/x/build v0.0.0-20210220033112-f539cd3e8d00 // indirect + golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 // indirect + golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d + golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect + golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 // indirect golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 ) diff --git a/go.sum b/go.sum index 4566d3677ea..22a8d0e02e5 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,145 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.44.3/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.75.0/go.mod h1:VGuuCn7PG0dwsd5XPVm2Mm3wlh3EL55/79EKB6hlPTY= +cloud.google.com/go v0.77.0 h1:qA5V5+uQf6Mgr+tmFI8UT3D/ELyhIYkPwNGao/3Y+sQ= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.13.0 h1:amPvhCOI+Hltp6rPu+62YdwhIrjf+34PKVAL4HwgYwk= +cloud.google.com/go/storage v1.13.0/go.mod h1:pqFyBUK3zZqMIIU5+8NaZq6/Ma3ClgUg9Hv5jfuJnvo= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= +github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= +github.com/aws/aws-sdk-go v1.30.15/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/bradfitz/go-smtpd v0.0.0-20170404230938-deb6d6237625/go.mod h1:HYsPBTaaSFSlLx/70C2HPIMNZpVV8+vt/A+FMnYP11g= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/coreos/go-systemd v0.0.0-20181012123002-c6f51f82210d/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/gliderlabs/ssh v0.1.1/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201218002935-b9804c9f04c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= +github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jellevandenhooff/dkim v0.0.0-20150330215556-f50fe3d243e1/go.mod h1:E0B/fFc00Y+Rasa88328GlI/XbtyysCtTHZS8h7IrBU= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.3/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= @@ -12,26 +148,346 @@ github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA= github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1 h1:ruQGxdhGHe7FWOJPT0mKs5+pD2Xs1Bm/kdGlHO04FmM= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.2 h1:YjHC5TgyMmHpicTgEqDN0Q96Xo8K6tLXPnmNOHXCgs0= +github.com/yuin/goldmark v1.3.2/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go4.org v0.0.0-20180809161055-417644f6feb5/go.mod h1:MkTOUMDaeVYJUOUsaDXIhWPZYa1yOyC1qaOBpL57BhE= +golang.org/x/build v0.0.0-20210220033112-f539cd3e8d00 h1:50GaO5zSxqEh98/N4wYkwQgJ70VCudD9FBmovm0v1jA= +golang.org/x/build v0.0.0-20210220033112-f539cd3e8d00/go.mod h1:ityaYXTAMnrXJU3nRnHDFVPeB9RM8WqAqjITWJ12ipw= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83 h1:/ZScEX8SfEmUGRHs0gxpqteO5nfNW6axyZbBdw9A12g= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1 h1:Kvvh58BN8Y9/lBi7hTekvtMpm07eUZ0ck5pRHpsMWrY= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210119194325-5f4716e94777 h1:003p0dJM77cxMSyCPFphvZf/Y5/NXf5fzg6ufd1/Oew= golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d h1:1aflnvSoWWLI2k/dMUAl5lvU1YO4Mb4hz0gh+1rjcxU= +golang.org/x/net v0.0.0-20210220033124-5f55cee0dc0d/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210113205817-d3ed898aa8a3/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/perf v0.0.0-20180704124530-6e6d33e29852/go.mod h1:JLpeXjPJfIyPr5TlbXLkXWLhP8nz10XfvxElABhCtcw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a h1:DcqTD9SDLc+1P/r1EmRBwnVsrOwW+kk2vWf9n+1sGhs= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 h1:SgQ6LNaYJU0JIuEHv9+s6EbhSCwYeAf5Yvj6lpYlqAE= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4 h1:0YWbFKbhXG/wIiuHDSKpS0Iy7FSA+u45VtBMfQcFTTc= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 h1:Hir2P/De0WpUhtrKGGjvSb2YxUgyZ7EFOSLIcSSpiwE= golang.org/x/time v0.0.0-20201208040808-7e3f01d25324/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e h1:FDhOuMEY4JVRztM/gsbk+IKUQ8kj74bxZrgw87eMMVc= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0 h1:po9/4sTYwZU9lPhi1tOrb4hCv3qrhiQ77LZfGa2OjwY= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.38.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210203152818-3206188e46ba/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +grpc.go4.org v0.0.0-20170609214715-11d0a25b4919/go.mod h1:77eQGdRu53HpSqPFJFmuJdjuHRquDANNeA4x7B8WQ9o= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/healthchecks.go b/healthchecks.go index f073eff058c..ad8adf2b8d2 100644 --- a/healthchecks.go +++ b/healthchecks.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -70,9 +72,9 @@ type HealthcheckResponse struct { // Healthchecks returns all healthchecks for a zone. // // API reference: https://api.cloudflare.com/#health-checks-list-health-checks -func (api *API) Healthchecks(zoneID string) ([]Healthcheck, error) { +func (api *API) Healthchecks(ctx context.Context, zoneID string) ([]Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []Healthcheck{}, err } @@ -87,9 +89,9 @@ func (api *API) Healthchecks(zoneID string) ([]Healthcheck, error) { // Healthcheck returns a single healthcheck by ID. // // API reference: https://api.cloudflare.com/#health-checks-health-check-details -func (api *API) Healthcheck(zoneID, healthcheckID string) (Healthcheck, error) { +func (api *API) Healthcheck(ctx context.Context, zoneID, healthcheckID string) (Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks/" + healthcheckID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return Healthcheck{}, err } @@ -104,9 +106,9 @@ func (api *API) Healthcheck(zoneID, healthcheckID string) (Healthcheck, error) { // CreateHealthcheck creates a new healthcheck in a zone. // // API reference: https://api.cloudflare.com/#health-checks-create-health-check -func (api *API) CreateHealthcheck(zoneID string, healthcheck Healthcheck) (Healthcheck, error) { +func (api *API) CreateHealthcheck(ctx context.Context, zoneID string, healthcheck Healthcheck) (Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks" - res, err := api.makeRequest("POST", uri, healthcheck) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, healthcheck) if err != nil { return Healthcheck{}, err } @@ -121,9 +123,9 @@ func (api *API) CreateHealthcheck(zoneID string, healthcheck Healthcheck) (Healt // UpdateHealthcheck updates an existing healthcheck. // // API reference: https://api.cloudflare.com/#health-checks-update-health-check -func (api *API) UpdateHealthcheck(zoneID string, healthcheckID string, healthcheck Healthcheck) (Healthcheck, error) { +func (api *API) UpdateHealthcheck(ctx context.Context, zoneID string, healthcheckID string, healthcheck Healthcheck) (Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks/" + healthcheckID - res, err := api.makeRequest("PUT", uri, healthcheck) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, healthcheck) if err != nil { return Healthcheck{}, err } @@ -138,9 +140,9 @@ func (api *API) UpdateHealthcheck(zoneID string, healthcheckID string, healthche // DeleteHealthcheck deletes a healthcheck in a zone. // // API reference: https://api.cloudflare.com/#health-checks-delete-health-check -func (api *API) DeleteHealthcheck(zoneID string, healthcheckID string) error { +func (api *API) DeleteHealthcheck(ctx context.Context, zoneID string, healthcheckID string) error { uri := "/zones/" + zoneID + "/healthchecks/" + healthcheckID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -155,9 +157,9 @@ func (api *API) DeleteHealthcheck(zoneID string, healthcheckID string) error { // CreateHealthcheckPreview creates a new preview of a healthcheck in a zone. // // API reference: https://api.cloudflare.com/#health-checks-create-preview-health-check -func (api *API) CreateHealthcheckPreview(zoneID string, healthcheck Healthcheck) (Healthcheck, error) { +func (api *API) CreateHealthcheckPreview(ctx context.Context, zoneID string, healthcheck Healthcheck) (Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks/preview" - res, err := api.makeRequest("POST", uri, healthcheck) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, healthcheck) if err != nil { return Healthcheck{}, err } @@ -172,9 +174,9 @@ func (api *API) CreateHealthcheckPreview(zoneID string, healthcheck Healthcheck) // HealthcheckPreview returns a single healthcheck preview by its ID. // // API reference: https://api.cloudflare.com/#health-checks-health-check-preview-details -func (api *API) HealthcheckPreview(zoneID, id string) (Healthcheck, error) { +func (api *API) HealthcheckPreview(ctx context.Context, zoneID, id string) (Healthcheck, error) { uri := "/zones/" + zoneID + "/healthchecks/preview/" + id - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return Healthcheck{}, err } @@ -189,9 +191,9 @@ func (api *API) HealthcheckPreview(zoneID, id string) (Healthcheck, error) { // DeleteHealthcheckPreview deletes a healthcheck preview in a zone if it exists. // // API reference: https://api.cloudflare.com/#health-checks-delete-preview-health-check -func (api *API) DeleteHealthcheckPreview(zoneID string, id string) error { +func (api *API) DeleteHealthcheckPreview(ctx context.Context, zoneID string, id string) error { uri := "/zones/" + zoneID + "/healthchecks/preview/" + id - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/healthchecks_test.go b/healthchecks_test.go index 27c5cc0abc8..b3ee7b95bc7 100644 --- a/healthchecks_test.go +++ b/healthchecks_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -75,7 +76,7 @@ var ( Type: "HTTP", CheckRegions: []string{"WNAM"}, HTTPConfig: &HealthcheckHTTPConfig{ - Method: "GET", + Method: http.MethodGet, Path: "/", Port: 8443, ExpectedBody: "", @@ -83,7 +84,7 @@ var ( FollowRedirects: true, AllowInsecure: false, Header: map[string][]string{ - "Host": []string{"www.example.com"}, + "Host": {"www.example.com"}, }, }, Notification: HealthcheckNotification{ @@ -100,7 +101,7 @@ func TestHealthchecks(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -123,7 +124,7 @@ func TestHealthchecks(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks", handler) want := []Healthcheck{expectedHealthcheck} - actual, err := client.Healthchecks(testZoneID) + actual, err := client.Healthchecks(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -134,7 +135,7 @@ func TestHealthcheck(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -148,7 +149,7 @@ func TestHealthcheck(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/"+healthcheckID, handler) want := expectedHealthcheck - actual, err := client.Healthcheck(testZoneID, healthcheckID) + actual, err := client.Healthcheck(context.TODO(), testZoneID, healthcheckID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -164,7 +165,7 @@ func TestCreateHealthcheck(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -178,7 +179,7 @@ func TestCreateHealthcheck(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks", handler) want := expectedHealthcheck - actual, err := client.CreateHealthcheck(testZoneID, newHealthcheck) + actual, err := client.CreateHealthcheck(context.TODO(), testZoneID, newHealthcheck) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -196,7 +197,7 @@ func TestUpdateHealthcheck(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -210,7 +211,7 @@ func TestUpdateHealthcheck(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/"+healthcheckID, handler) want := expectedHealthcheck - actual, err := client.UpdateHealthcheck(testZoneID, healthcheckID, updatedHealthcheck) + actual, err := client.UpdateHealthcheck(context.TODO(), testZoneID, healthcheckID, updatedHealthcheck) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -221,7 +222,7 @@ func TestDeleteHealthcheck(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": null, @@ -234,7 +235,7 @@ func TestDeleteHealthcheck(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/"+healthcheckID, handler) - err := client.DeleteHealthcheck(testZoneID, healthcheckID) + err := client.DeleteHealthcheck(context.TODO(), testZoneID, healthcheckID) assert.NoError(t, err) } @@ -248,7 +249,7 @@ func TestCreateHealthcheckPreview(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -262,7 +263,7 @@ func TestCreateHealthcheckPreview(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/preview", handler) want := expectedHealthcheck - actual, err := client.CreateHealthcheckPreview(testZoneID, newHealthcheck) + actual, err := client.CreateHealthcheckPreview(context.TODO(), testZoneID, newHealthcheck) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -273,7 +274,7 @@ func TestHealthcheckPreview(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -287,7 +288,7 @@ func TestHealthcheckPreview(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/preview/"+healthcheckID, handler) want := expectedHealthcheck - actual, err := client.HealthcheckPreview(testZoneID, healthcheckID) + actual, err := client.HealthcheckPreview(context.TODO(), testZoneID, healthcheckID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -298,7 +299,7 @@ func TestDeleteHealthcheckPreview(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": null, @@ -311,6 +312,6 @@ func TestDeleteHealthcheckPreview(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/healthchecks/preview/"+healthcheckID, handler) - err := client.DeleteHealthcheckPreview(testZoneID, healthcheckID) + err := client.DeleteHealthcheckPreview(context.TODO(), testZoneID, healthcheckID) assert.NoError(t, err) } diff --git a/ip_address_management_test.go b/ip_address_management_test.go index c19b62e3c3b..9af0ed9fa24 100644 --- a/ip_address_management_test.go +++ b/ip_address_management_test.go @@ -15,7 +15,7 @@ func TestListIPPrefix(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": [ @@ -71,7 +71,7 @@ func TestGetIPPrefix(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -175,7 +175,7 @@ func TestGetAdvertisementStatus(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { diff --git a/ip_list_test.go b/ip_list_test.go index c7ab7b257fb..9a6d2300ca1 100644 --- a/ip_list_test.go +++ b/ip_list_test.go @@ -15,7 +15,7 @@ func TestListIPLists(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": [ @@ -65,7 +65,7 @@ func TestCreateIPList(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -111,7 +111,7 @@ func TestGetIPList(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -157,7 +157,7 @@ func TestUpdateIPList(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -204,7 +204,7 @@ func TestDeleteIPList(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -235,7 +235,7 @@ func TestListIPListsItems(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") if len(r.URL.Query().Get("cursor")) > 0 && r.URL.Query().Get("cursor") == "yyy" { @@ -316,7 +316,7 @@ func TestCreateIPListItems(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -354,7 +354,7 @@ func TestReplaceIPListItems(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -392,7 +392,7 @@ func TestDeleteIPListItems(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -426,7 +426,7 @@ func TestGetIPListItem(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { diff --git a/ips_test.go b/ips_test.go index 30b6c14e8ee..c73b07e3476 100644 --- a/ips_test.go +++ b/ips_test.go @@ -43,7 +43,7 @@ func Test_IPs(t *testing.T) { defer func() { http.DefaultTransport = defaultTransport }() mux.HandleFunc("/ips", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{ "success": true, diff --git a/load_balancing.go b/load_balancing.go index e092d4e6b80..b545ce8abc2 100644 --- a/load_balancing.go +++ b/load_balancing.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -217,9 +219,9 @@ type loadBalancerPoolHealthResponse struct { // CreateLoadBalancerPool creates a new load balancer pool. // // API reference: https://api.cloudflare.com/#load-balancer-pools-create-pool -func (api *API) CreateLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { +func (api *API) CreateLoadBalancerPool(ctx context.Context, pool LoadBalancerPool) (LoadBalancerPool, error) { uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("POST", uri, pool) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, pool) if err != nil { return LoadBalancerPool{}, err } @@ -233,9 +235,9 @@ func (api *API) CreateLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, // ListLoadBalancerPools lists load balancer pools connected to an account. // // API reference: https://api.cloudflare.com/#load-balancer-pools-list-pools -func (api *API) ListLoadBalancerPools() ([]LoadBalancerPool, error) { +func (api *API) ListLoadBalancerPools(ctx context.Context) ([]LoadBalancerPool, error) { uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -249,9 +251,9 @@ func (api *API) ListLoadBalancerPools() ([]LoadBalancerPool, error) { // LoadBalancerPoolDetails returns the details for a load balancer pool. // // API reference: https://api.cloudflare.com/#load-balancer-pools-pool-details -func (api *API) LoadBalancerPoolDetails(poolID string) (LoadBalancerPool, error) { +func (api *API) LoadBalancerPoolDetails(ctx context.Context, poolID string) (LoadBalancerPool, error) { uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LoadBalancerPool{}, err } @@ -265,9 +267,9 @@ func (api *API) LoadBalancerPoolDetails(poolID string) (LoadBalancerPool, error) // DeleteLoadBalancerPool disables and deletes a load balancer pool. // // API reference: https://api.cloudflare.com/#load-balancer-pools-delete-pool -func (api *API) DeleteLoadBalancerPool(poolID string) error { +func (api *API) DeleteLoadBalancerPool(ctx context.Context, poolID string) error { uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { + if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { return err } return nil @@ -276,9 +278,9 @@ func (api *API) DeleteLoadBalancerPool(poolID string) error { // ModifyLoadBalancerPool modifies a configured load balancer pool. // // API reference: https://api.cloudflare.com/#load-balancer-pools-update-pool -func (api *API) ModifyLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { +func (api *API) ModifyLoadBalancerPool(ctx context.Context, pool LoadBalancerPool) (LoadBalancerPool, error) { uri := api.userBaseURL("/user") + "/load_balancers/pools/" + pool.ID - res, err := api.makeRequest("PUT", uri, pool) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, pool) if err != nil { return LoadBalancerPool{}, err } @@ -292,9 +294,9 @@ func (api *API) ModifyLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, // CreateLoadBalancerMonitor creates a new load balancer monitor. // // API reference: https://api.cloudflare.com/#load-balancer-monitors-create-monitor -func (api *API) CreateLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { +func (api *API) CreateLoadBalancerMonitor(ctx context.Context, monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("POST", uri, monitor) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, monitor) if err != nil { return LoadBalancerMonitor{}, err } @@ -308,9 +310,9 @@ func (api *API) CreateLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBala // ListLoadBalancerMonitors lists load balancer monitors connected to an account. // // API reference: https://api.cloudflare.com/#load-balancer-monitors-list-monitors -func (api *API) ListLoadBalancerMonitors() ([]LoadBalancerMonitor, error) { +func (api *API) ListLoadBalancerMonitors(ctx context.Context) ([]LoadBalancerMonitor, error) { uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -324,9 +326,9 @@ func (api *API) ListLoadBalancerMonitors() ([]LoadBalancerMonitor, error) { // LoadBalancerMonitorDetails returns the details for a load balancer monitor. // // API reference: https://api.cloudflare.com/#load-balancer-monitors-monitor-details -func (api *API) LoadBalancerMonitorDetails(monitorID string) (LoadBalancerMonitor, error) { +func (api *API) LoadBalancerMonitorDetails(ctx context.Context, monitorID string) (LoadBalancerMonitor, error) { uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LoadBalancerMonitor{}, err } @@ -340,9 +342,9 @@ func (api *API) LoadBalancerMonitorDetails(monitorID string) (LoadBalancerMonito // DeleteLoadBalancerMonitor disables and deletes a load balancer monitor. // // API reference: https://api.cloudflare.com/#load-balancer-monitors-delete-monitor -func (api *API) DeleteLoadBalancerMonitor(monitorID string) error { +func (api *API) DeleteLoadBalancerMonitor(ctx context.Context, monitorID string) error { uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { + if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { return err } return nil @@ -351,9 +353,9 @@ func (api *API) DeleteLoadBalancerMonitor(monitorID string) error { // ModifyLoadBalancerMonitor modifies a configured load balancer monitor. // // API reference: https://api.cloudflare.com/#load-balancer-monitors-update-monitor -func (api *API) ModifyLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { +func (api *API) ModifyLoadBalancerMonitor(ctx context.Context, monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitor.ID - res, err := api.makeRequest("PUT", uri, monitor) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, monitor) if err != nil { return LoadBalancerMonitor{}, err } @@ -367,9 +369,9 @@ func (api *API) ModifyLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBala // CreateLoadBalancer creates a new load balancer. // // API reference: https://api.cloudflare.com/#load-balancers-create-load-balancer -func (api *API) CreateLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { +func (api *API) CreateLoadBalancer(ctx context.Context, zoneID string, lb LoadBalancer) (LoadBalancer, error) { uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("POST", uri, lb) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, lb) if err != nil { return LoadBalancer{}, err } @@ -383,9 +385,9 @@ func (api *API) CreateLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer // ListLoadBalancers lists load balancers configured on a zone. // // API reference: https://api.cloudflare.com/#load-balancers-list-load-balancers -func (api *API) ListLoadBalancers(zoneID string) ([]LoadBalancer, error) { +func (api *API) ListLoadBalancers(ctx context.Context, zoneID string) ([]LoadBalancer, error) { uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -399,9 +401,9 @@ func (api *API) ListLoadBalancers(zoneID string) ([]LoadBalancer, error) { // LoadBalancerDetails returns the details for a load balancer. // // API reference: https://api.cloudflare.com/#load-balancers-load-balancer-details -func (api *API) LoadBalancerDetails(zoneID, lbID string) (LoadBalancer, error) { +func (api *API) LoadBalancerDetails(ctx context.Context, zoneID, lbID string) (LoadBalancer, error) { uri := "/zones/" + zoneID + "/load_balancers/" + lbID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LoadBalancer{}, err } @@ -415,9 +417,9 @@ func (api *API) LoadBalancerDetails(zoneID, lbID string) (LoadBalancer, error) { // DeleteLoadBalancer disables and deletes a load balancer. // // API reference: https://api.cloudflare.com/#load-balancers-delete-load-balancer -func (api *API) DeleteLoadBalancer(zoneID, lbID string) error { +func (api *API) DeleteLoadBalancer(ctx context.Context, zoneID, lbID string) error { uri := "/zones/" + zoneID + "/load_balancers/" + lbID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { + if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { return err } return nil @@ -426,9 +428,9 @@ func (api *API) DeleteLoadBalancer(zoneID, lbID string) error { // ModifyLoadBalancer modifies a configured load balancer. // // API reference: https://api.cloudflare.com/#load-balancers-update-load-balancer -func (api *API) ModifyLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { +func (api *API) ModifyLoadBalancer(ctx context.Context, zoneID string, lb LoadBalancer) (LoadBalancer, error) { uri := "/zones/" + zoneID + "/load_balancers/" + lb.ID - res, err := api.makeRequest("PUT", uri, lb) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, lb) if err != nil { return LoadBalancer{}, err } @@ -442,9 +444,9 @@ func (api *API) ModifyLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer // PoolHealthDetails fetches the latest healtcheck details for a single pool. // // API reference: https://api.cloudflare.com/#load-balancer-pools-pool-health-details -func (api *API) PoolHealthDetails(poolID string) (LoadBalancerPoolHealth, error) { +func (api *API) PoolHealthDetails(ctx context.Context, poolID string) (LoadBalancerPoolHealth, error) { uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID + "/health" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LoadBalancerPoolHealth{}, err } diff --git a/load_balancing_example_test.go b/load_balancing_example_test.go index 7f0786539c7..1905f4c6e95 100644 --- a/load_balancing_example_test.go +++ b/load_balancing_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + context "context" "fmt" "log" @@ -21,7 +22,7 @@ func ExampleAPI_ListLoadBalancers() { } // List LBs configured in zone. - lbList, err := api.ListLoadBalancers(id) + lbList, err := api.ListLoadBalancers(context.TODO(), id) if err != nil { log.Fatal(err) } @@ -39,7 +40,7 @@ func ExampleAPI_PoolHealthDetails() { } // Fetch pool health details. - healthInfo, err := api.PoolHealthDetails("example-pool-id") + healthInfo, err := api.PoolHealthDetails(context.TODO(), "example-pool-id") if err != nil { log.Fatal(err) } diff --git a/load_balancing_test.go b/load_balancing_test.go index 697f9eeae13..64205584454 100644 --- a/load_balancing_test.go +++ b/load_balancing_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "io/ioutil" "net/http" @@ -15,7 +16,7 @@ func TestCreateLoadBalancerPool(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -112,7 +113,7 @@ func TestCreateLoadBalancerPool(t *testing.T) { }, } - actual, err := client.CreateLoadBalancerPool(request) + actual, err := client.CreateLoadBalancerPool(context.TODO(), request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -123,7 +124,7 @@ func TestListLoadBalancerPools(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -182,7 +183,7 @@ func TestListLoadBalancerPools(t *testing.T) { }, } - actual, err := client.ListLoadBalancerPools() + actual, err := client.ListLoadBalancerPools(context.TODO()) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -193,7 +194,7 @@ func TestLoadBalancerPoolDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -242,12 +243,12 @@ func TestLoadBalancerPoolDetails(t *testing.T) { NotificationEmail: "someone@example.com", } - actual, err := client.LoadBalancerPoolDetails("17b5962d775c646f3f9725cbc7a53df4") + actual, err := client.LoadBalancerPoolDetails(context.TODO(), "17b5962d775c646f3f9725cbc7a53df4") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.LoadBalancerPoolDetails("bar") + _, err = client.LoadBalancerPoolDetails(context.TODO(), "bar") assert.Error(t, err) } @@ -256,7 +257,7 @@ func TestDeleteLoadBalancerPool(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -269,8 +270,8 @@ func TestDeleteLoadBalancerPool(t *testing.T) { } mux.HandleFunc("/user/load_balancers/pools/17b5962d775c646f3f9725cbc7a53df4", handler) - assert.NoError(t, client.DeleteLoadBalancerPool("17b5962d775c646f3f9725cbc7a53df4")) - assert.Error(t, client.DeleteLoadBalancerPool("bar")) + assert.NoError(t, client.DeleteLoadBalancerPool(context.TODO(), "17b5962d775c646f3f9725cbc7a53df4")) + assert.Error(t, client.DeleteLoadBalancerPool(context.TODO(), "bar")) } func TestModifyLoadBalancerPool(t *testing.T) { @@ -278,7 +279,7 @@ func TestModifyLoadBalancerPool(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -371,7 +372,7 @@ func TestModifyLoadBalancerPool(t *testing.T) { }, } - actual, err := client.ModifyLoadBalancerPool(request) + actual, err := client.ModifyLoadBalancerPool(context.TODO(), request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -382,7 +383,7 @@ func TestCreateLoadBalancerMonitor(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -451,7 +452,7 @@ func TestCreateLoadBalancerMonitor(t *testing.T) { ModifiedOn: &modifiedOn, Type: "https", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/health", Header: map[string][]string{ "Host": {"example.com"}, @@ -469,7 +470,7 @@ func TestCreateLoadBalancerMonitor(t *testing.T) { request := LoadBalancerMonitor{ Type: "https", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/health", Header: map[string][]string{ "Host": {"example.com"}, @@ -485,7 +486,7 @@ func TestCreateLoadBalancerMonitor(t *testing.T) { AllowInsecure: true, } - actual, err := client.CreateLoadBalancerMonitor(request) + actual, err := client.CreateLoadBalancerMonitor(context.TODO(), request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -496,7 +497,7 @@ func TestListLoadBalancerMonitors(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -545,7 +546,7 @@ func TestListLoadBalancerMonitors(t *testing.T) { ModifiedOn: &modifiedOn, Type: "https", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/health", Header: map[string][]string{ "Host": {"example.com"}, @@ -559,7 +560,7 @@ func TestListLoadBalancerMonitors(t *testing.T) { }, } - actual, err := client.ListLoadBalancerMonitors() + actual, err := client.ListLoadBalancerMonitors(context.TODO()) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -570,7 +571,7 @@ func TestLoadBalancerMonitorDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -613,7 +614,7 @@ func TestLoadBalancerMonitorDetails(t *testing.T) { ModifiedOn: &modifiedOn, Type: "https", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/health", Header: map[string][]string{ "Host": {"example.com"}, @@ -629,12 +630,12 @@ func TestLoadBalancerMonitorDetails(t *testing.T) { AllowInsecure: true, } - actual, err := client.LoadBalancerMonitorDetails("f1aba936b94213e5b8dca0c0dbf1f9cc") + actual, err := client.LoadBalancerMonitorDetails(context.TODO(), "f1aba936b94213e5b8dca0c0dbf1f9cc") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.LoadBalancerMonitorDetails("bar") + _, err = client.LoadBalancerMonitorDetails(context.TODO(), "bar") assert.Error(t, err) } @@ -643,7 +644,7 @@ func TestDeleteLoadBalancerMonitor(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -656,8 +657,8 @@ func TestDeleteLoadBalancerMonitor(t *testing.T) { } mux.HandleFunc("/user/load_balancers/monitors/f1aba936b94213e5b8dca0c0dbf1f9cc", handler) - assert.NoError(t, client.DeleteLoadBalancerMonitor("f1aba936b94213e5b8dca0c0dbf1f9cc")) - assert.Error(t, client.DeleteLoadBalancerMonitor("bar")) + assert.NoError(t, client.DeleteLoadBalancerMonitor(context.TODO(), "f1aba936b94213e5b8dca0c0dbf1f9cc")) + assert.Error(t, client.DeleteLoadBalancerMonitor(context.TODO(), "bar")) } func TestModifyLoadBalancerMonitor(t *testing.T) { @@ -665,7 +666,7 @@ func TestModifyLoadBalancerMonitor(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -735,7 +736,7 @@ func TestModifyLoadBalancerMonitor(t *testing.T) { ModifiedOn: &modifiedOn, Type: "http", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/status", Header: map[string][]string{ "Host": {"example.com"}, @@ -754,7 +755,7 @@ func TestModifyLoadBalancerMonitor(t *testing.T) { ID: "f1aba936b94213e5b8dca0c0dbf1f9cc", Type: "http", Description: "Login page monitor", - Method: "GET", + Method: http.MethodGet, Path: "/status", Header: map[string][]string{ "Host": {"example.com"}, @@ -770,7 +771,7 @@ func TestModifyLoadBalancerMonitor(t *testing.T) { AllowInsecure: true, } - actual, err := client.ModifyLoadBalancerMonitor(request) + actual, err := client.ModifyLoadBalancerMonitor(context.TODO(), request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -781,7 +782,7 @@ func TestCreateLoadBalancer(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -942,12 +943,12 @@ func TestCreateLoadBalancer(t *testing.T) { }, }, Rules: []*LoadBalancerRule{ - &LoadBalancerRule{ + { Name: "example rule", Condition: "cf.load_balancer.region == \"SAF\"", Overrides: LoadBalancerRuleOverrides{ RegionPools: map[string][]string{ - "SAF": []string{"de90f38ced07c2e2f4df50b1f61d4194"}, + "SAF": {"de90f38ced07c2e2f4df50b1f61d4194"}, }, }, }, @@ -994,12 +995,12 @@ func TestCreateLoadBalancer(t *testing.T) { }, }, Rules: []*LoadBalancerRule{ - &LoadBalancerRule{ + { Name: "example rule", Condition: "cf.load_balancer.region == \"SAF\"", Overrides: LoadBalancerRuleOverrides{ RegionPools: map[string][]string{ - "SAF": []string{"de90f38ced07c2e2f4df50b1f61d4194"}, + "SAF": {"de90f38ced07c2e2f4df50b1f61d4194"}, }, }, }, @@ -1014,7 +1015,7 @@ func TestCreateLoadBalancer(t *testing.T) { }, } - actual, err := client.CreateLoadBalancer("199d98642c564d2e855e9661899b7252", request) + actual, err := client.CreateLoadBalancer(context.TODO(), "199d98642c564d2e855e9661899b7252", request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -1025,7 +1026,7 @@ func TestListLoadBalancers(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -1122,7 +1123,7 @@ func TestListLoadBalancers(t *testing.T) { }, } - actual, err := client.ListLoadBalancers("199d98642c564d2e855e9661899b7252") + actual, err := client.ListLoadBalancers(context.TODO(), "199d98642c564d2e855e9661899b7252") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -1133,7 +1134,7 @@ func TestLoadBalancerDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -1220,12 +1221,12 @@ func TestLoadBalancerDetails(t *testing.T) { Proxied: true, } - actual, err := client.LoadBalancerDetails("199d98642c564d2e855e9661899b7252", "699d98642c564d2e855e9661899b7252") + actual, err := client.LoadBalancerDetails(context.TODO(), "199d98642c564d2e855e9661899b7252", "699d98642c564d2e855e9661899b7252") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.LoadBalancerDetails("199d98642c564d2e855e9661899b7252", "bar") + _, err = client.LoadBalancerDetails(context.TODO(), "199d98642c564d2e855e9661899b7252", "bar") assert.Error(t, err) } @@ -1234,7 +1235,7 @@ func TestDeleteLoadBalancer(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -1247,8 +1248,8 @@ func TestDeleteLoadBalancer(t *testing.T) { } mux.HandleFunc("/zones/199d98642c564d2e855e9661899b7252/load_balancers/699d98642c564d2e855e9661899b7252", handler) - assert.NoError(t, client.DeleteLoadBalancer("199d98642c564d2e855e9661899b7252", "699d98642c564d2e855e9661899b7252")) - assert.Error(t, client.DeleteLoadBalancer("199d98642c564d2e855e9661899b7252", "bar")) + assert.NoError(t, client.DeleteLoadBalancer(context.TODO(), "199d98642c564d2e855e9661899b7252", "699d98642c564d2e855e9661899b7252")) + assert.Error(t, client.DeleteLoadBalancer(context.TODO(), "199d98642c564d2e855e9661899b7252", "bar")) } func TestModifyLoadBalancer(t *testing.T) { @@ -1256,7 +1257,7 @@ func TestModifyLoadBalancer(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -1417,7 +1418,7 @@ func TestModifyLoadBalancer(t *testing.T) { }, } - actual, err := client.ModifyLoadBalancer("199d98642c564d2e855e9661899b7252", request) + actual, err := client.ModifyLoadBalancer(context.TODO(), "199d98642c564d2e855e9661899b7252", request) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -1428,7 +1429,7 @@ func TestLoadBalancerPoolHealthDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -1462,7 +1463,7 @@ func TestLoadBalancerPoolHealthDetails(t *testing.T) { "Amsterdam, NL": { Healthy: true, Origins: []map[string]LoadBalancerOriginHealth{ - map[string]LoadBalancerOriginHealth{ + { "2001:DB8::5": { Healthy: true, RTT: Duration{12*time.Millisecond + 100*time.Microsecond}, @@ -1475,7 +1476,7 @@ func TestLoadBalancerPoolHealthDetails(t *testing.T) { }, } - actual, err := client.PoolHealthDetails("699d98642c564d2e855e9661899b7252") + actual, err := client.PoolHealthDetails(context.TODO(), "699d98642c564d2e855e9661899b7252") if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/lockdown.go b/lockdown.go index d3e91bb8156..16db13c8386 100644 --- a/lockdown.go +++ b/lockdown.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" @@ -45,9 +47,9 @@ type ZoneLockdownListResponse struct { // CreateZoneLockdown creates a Zone ZoneLockdown rule for the given zone ID. // // API reference: https://api.cloudflare.com/#zone-ZoneLockdown-create-a-ZoneLockdown-rule -func (api *API) CreateZoneLockdown(zoneID string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { +func (api *API) CreateZoneLockdown(ctx context.Context, zoneID string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { uri := "/zones/" + zoneID + "/firewall/lockdowns" - res, err := api.makeRequest("POST", uri, ld) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ld) if err != nil { return nil, err } @@ -65,9 +67,9 @@ func (api *API) CreateZoneLockdown(zoneID string, ld ZoneLockdown) (*ZoneLockdow // given zone ID. // // API reference: https://api.cloudflare.com/#zone-ZoneLockdown-update-ZoneLockdown-rule -func (api *API) UpdateZoneLockdown(zoneID string, id string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { +func (api *API) UpdateZoneLockdown(ctx context.Context, zoneID string, id string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("PUT", uri, ld) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, ld) if err != nil { return nil, err } @@ -85,9 +87,9 @@ func (api *API) UpdateZoneLockdown(zoneID string, id string, ld ZoneLockdown) (* // given zone ID. // // API reference: https://api.cloudflare.com/#zone-ZoneLockdown-delete-ZoneLockdown-rule -func (api *API) DeleteZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { +func (api *API) DeleteZoneLockdown(ctx context.Context, zoneID string, id string) (*ZoneLockdownResponse, error) { uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return nil, err } @@ -105,9 +107,9 @@ func (api *API) DeleteZoneLockdown(zoneID string, id string) (*ZoneLockdownRespo // given zone ID. // // API reference: https://api.cloudflare.com/#zone-ZoneLockdown-ZoneLockdown-rule-details -func (api *API) ZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { +func (api *API) ZoneLockdown(ctx context.Context, zoneID string, id string) (*ZoneLockdownResponse, error) { uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -125,7 +127,7 @@ func (api *API) ZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, e // zone ID by page number. // // API reference: https://api.cloudflare.com/#zone-ZoneLockdown-list-ZoneLockdown-rules -func (api *API) ListZoneLockdowns(zoneID string, page int) (*ZoneLockdownListResponse, error) { +func (api *API) ListZoneLockdowns(ctx context.Context, zoneID string, page int) (*ZoneLockdownListResponse, error) { v := url.Values{} if page <= 0 { page = 1 @@ -136,7 +138,7 @@ func (api *API) ListZoneLockdowns(zoneID string, page int) (*ZoneLockdownListRes query := "?" + v.Encode() uri := "/zones/" + zoneID + "/firewall/lockdowns" + query - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } diff --git a/lockdown_example_test.go b/lockdown_example_test.go index 611acbf001f..be4943a4376 100644 --- a/lockdown_example_test.go +++ b/lockdown_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" "strings" @@ -20,7 +21,7 @@ func ExampleAPI_ListZoneLockdowns_all() { } // Fetch all Zone Lockdown rules for a zone, by page. - rules, err := api.ListZoneLockdowns(zoneID, 1) + rules, err := api.ListZoneLockdowns(context.TODO(), zoneID, 1) if err != nil { log.Fatal(err) } @@ -47,7 +48,7 @@ func ExampleAPI_CreateZoneLockdown() { "*.example.org/test", }, Configurations: []cloudflare.ZoneLockdownConfig{ - cloudflare.ZoneLockdownConfig{ + { Target: "ip", Value: "127.0.0.1", }, @@ -56,7 +57,7 @@ func ExampleAPI_CreateZoneLockdown() { Priority: 1, } - response, err := api.CreateZoneLockdown(zoneID, newZoneLockdown) + response, err := api.CreateZoneLockdown(context.TODO(), zoneID, newZoneLockdown) if err != nil { log.Fatal(err) } diff --git a/logpull.go b/logpull.go index b03eb72a14e..6df9c763392 100644 --- a/logpull.go +++ b/logpull.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "github.com/pkg/errors" ) @@ -22,9 +24,9 @@ type LogpullRetentionConfigurationResponse struct { // GetLogpullRetentionFlag gets the current setting flag. // // API reference: https://developers.cloudflare.com/logs/logpull-api/enabling-log-retention/ -func (api *API) GetLogpullRetentionFlag(zoneID string) (*LogpullRetentionConfiguration, error) { +func (api *API) GetLogpullRetentionFlag(ctx context.Context, zoneID string) (*LogpullRetentionConfiguration, error) { uri := "/zones/" + zoneID + "/logs/control/retention/flag" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return &LogpullRetentionConfiguration{}, err } @@ -39,11 +41,11 @@ func (api *API) GetLogpullRetentionFlag(zoneID string) (*LogpullRetentionConfigu // SetLogpullRetentionFlag updates the retention flag to the defined boolean. // // API reference: https://developers.cloudflare.com/logs/logpull-api/enabling-log-retention/ -func (api *API) SetLogpullRetentionFlag(zoneID string, enabled bool) (*LogpullRetentionConfiguration, error) { +func (api *API) SetLogpullRetentionFlag(ctx context.Context, zoneID string, enabled bool) (*LogpullRetentionConfiguration, error) { uri := "/zones/" + zoneID + "/logs/control/retention/flag" flagPayload := LogpullRetentionConfiguration{Flag: enabled} - res, err := api.makeRequest("POST", uri, flagPayload) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, flagPayload) if err != nil { return &LogpullRetentionConfiguration{}, err } diff --git a/logpull_test.go b/logpull_test.go index 333a0258e88..0f6a3afbdcf 100644 --- a/logpull_test.go +++ b/logpull_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -13,7 +14,7 @@ func TestGetLogpullRetentionFlag(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "errors": [], @@ -28,7 +29,7 @@ func TestGetLogpullRetentionFlag(t *testing.T) { mux.HandleFunc("/zones/d56084adb405e0b7e32c52321bf07be6/logs/control/retention/flag", handler) want := &LogpullRetentionConfiguration{Flag: true} - actual, err := client.GetLogpullRetentionFlag("d56084adb405e0b7e32c52321bf07be6") + actual, err := client.GetLogpullRetentionFlag(context.TODO(), "d56084adb405e0b7e32c52321bf07be6") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -39,7 +40,7 @@ func TestSetLogpullRetentionFlag(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "errors": [], @@ -54,7 +55,7 @@ func TestSetLogpullRetentionFlag(t *testing.T) { mux.HandleFunc("/zones/d56084adb405e0b7e32c52321bf07be6/logs/control/retention/flag", handler) want := &LogpullRetentionConfiguration{Flag: false} - actual, err := client.SetLogpullRetentionFlag("d56084adb405e0b7e32c52321bf07be6", false) + actual, err := client.SetLogpullRetentionFlag(context.TODO(), "d56084adb405e0b7e32c52321bf07be6", false) if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/logpush.go b/logpush.go index 45ec987d0ae..9c0b4a938ff 100644 --- a/logpush.go +++ b/logpush.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "strconv" "time" @@ -93,9 +95,9 @@ type LogpushDestinationExistsRequest struct { // CreateLogpushJob creates a new LogpushJob for a zone. // // API reference: https://api.cloudflare.com/#logpush-jobs-create-logpush-job -func (api *API) CreateLogpushJob(zoneID string, job LogpushJob) (*LogpushJob, error) { +func (api *API) CreateLogpushJob(ctx context.Context, zoneID string, job LogpushJob) (*LogpushJob, error) { uri := "/zones/" + zoneID + "/logpush/jobs" - res, err := api.makeRequest("POST", uri, job) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, job) if err != nil { return nil, err } @@ -110,9 +112,9 @@ func (api *API) CreateLogpushJob(zoneID string, job LogpushJob) (*LogpushJob, er // LogpushJobs returns all Logpush Jobs for a zone. // // API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs -func (api *API) LogpushJobs(zoneID string) ([]LogpushJob, error) { +func (api *API) LogpushJobs(ctx context.Context, zoneID string) ([]LogpushJob, error) { uri := "/zones/" + zoneID + "/logpush/jobs" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []LogpushJob{}, err } @@ -127,9 +129,9 @@ func (api *API) LogpushJobs(zoneID string) ([]LogpushJob, error) { // LogpushJobsForDataset returns all Logpush Jobs for a dataset in a zone. // // API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs-for-a-dataset -func (api *API) LogpushJobsForDataset(zoneID, dataset string) ([]LogpushJob, error) { +func (api *API) LogpushJobsForDataset(ctx context.Context, zoneID, dataset string) ([]LogpushJob, error) { uri := "/zones/" + zoneID + "/logpush/datasets/" + dataset + "/jobs" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []LogpushJob{}, err } @@ -144,9 +146,9 @@ func (api *API) LogpushJobsForDataset(zoneID, dataset string) ([]LogpushJob, err // LogpushFields returns fields for a given dataset. // // API reference: https://api.cloudflare.com/#logpush-jobs-list-logpush-jobs -func (api *API) LogpushFields(zoneID, dataset string) (LogpushFields, error) { +func (api *API) LogpushFields(ctx context.Context, zoneID, dataset string) (LogpushFields, error) { uri := "/zones/" + zoneID + "/logpush/datasets/" + dataset + "/fields" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LogpushFields{}, err } @@ -161,9 +163,9 @@ func (api *API) LogpushFields(zoneID, dataset string) (LogpushFields, error) { // LogpushJob fetches detail about one Logpush Job for a zone. // // API reference: https://api.cloudflare.com/#logpush-jobs-logpush-job-details -func (api *API) LogpushJob(zoneID string, jobID int) (LogpushJob, error) { +func (api *API) LogpushJob(ctx context.Context, zoneID string, jobID int) (LogpushJob, error) { uri := "/zones/" + zoneID + "/logpush/jobs/" + strconv.Itoa(jobID) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return LogpushJob{}, err } @@ -178,9 +180,9 @@ func (api *API) LogpushJob(zoneID string, jobID int) (LogpushJob, error) { // UpdateLogpushJob lets you update a Logpush Job. // // API reference: https://api.cloudflare.com/#logpush-jobs-update-logpush-job -func (api *API) UpdateLogpushJob(zoneID string, jobID int, job LogpushJob) error { +func (api *API) UpdateLogpushJob(ctx context.Context, zoneID string, jobID int, job LogpushJob) error { uri := "/zones/" + zoneID + "/logpush/jobs/" + strconv.Itoa(jobID) - res, err := api.makeRequest("PUT", uri, job) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, job) if err != nil { return err } @@ -195,9 +197,9 @@ func (api *API) UpdateLogpushJob(zoneID string, jobID int, job LogpushJob) error // DeleteLogpushJob deletes a Logpush Job for a zone. // // API reference: https://api.cloudflare.com/#logpush-jobs-delete-logpush-job -func (api *API) DeleteLogpushJob(zoneID string, jobID int) error { +func (api *API) DeleteLogpushJob(ctx context.Context, zoneID string, jobID int) error { uri := "/zones/" + zoneID + "/logpush/jobs/" + strconv.Itoa(jobID) - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -212,9 +214,9 @@ func (api *API) DeleteLogpushJob(zoneID string, jobID int) error { // GetLogpushOwnershipChallenge returns ownership challenge. // // API reference: https://api.cloudflare.com/#logpush-jobs-get-ownership-challenge -func (api *API) GetLogpushOwnershipChallenge(zoneID, destinationConf string) (*LogpushGetOwnershipChallenge, error) { +func (api *API) GetLogpushOwnershipChallenge(ctx context.Context, zoneID, destinationConf string) (*LogpushGetOwnershipChallenge, error) { uri := "/zones/" + zoneID + "/logpush/ownership" - res, err := api.makeRequest("POST", uri, LogpushGetOwnershipChallengeRequest{ + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushGetOwnershipChallengeRequest{ DestinationConf: destinationConf, }) if err != nil { @@ -236,9 +238,9 @@ func (api *API) GetLogpushOwnershipChallenge(zoneID, destinationConf string) (*L // ValidateLogpushOwnershipChallenge returns ownership challenge validation result. // // API reference: https://api.cloudflare.com/#logpush-jobs-validate-ownership-challenge -func (api *API) ValidateLogpushOwnershipChallenge(zoneID, destinationConf, ownershipChallenge string) (bool, error) { +func (api *API) ValidateLogpushOwnershipChallenge(ctx context.Context, zoneID, destinationConf, ownershipChallenge string) (bool, error) { uri := "/zones/" + zoneID + "/logpush/ownership/validate" - res, err := api.makeRequest("POST", uri, LogpushValidateOwnershipChallengeRequest{ + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushValidateOwnershipChallengeRequest{ DestinationConf: destinationConf, OwnershipChallenge: ownershipChallenge, }) @@ -256,9 +258,9 @@ func (api *API) ValidateLogpushOwnershipChallenge(zoneID, destinationConf, owner // CheckLogpushDestinationExists returns destination exists check result. // // API reference: https://api.cloudflare.com/#logpush-jobs-check-destination-exists -func (api *API) CheckLogpushDestinationExists(zoneID, destinationConf string) (bool, error) { +func (api *API) CheckLogpushDestinationExists(ctx context.Context, zoneID, destinationConf string) (bool, error) { uri := "/zones/" + zoneID + "/logpush/validate/destination/exists" - res, err := api.makeRequest("POST", uri, LogpushDestinationExistsRequest{ + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, LogpushDestinationExistsRequest{ DestinationConf: destinationConf, }) if err != nil { diff --git a/logpush_example_test.go b/logpush_example_test.go index d4102242573..7f76226b0d2 100644 --- a/logpush_example_test.go +++ b/logpush_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -15,8 +16,8 @@ var exampleNewLogpushJob = cloudflare.LogpushJob{ } var exampleUpdatedLogpushJob = cloudflare.LogpushJob{ - Enabled: true, - Name: "updated.com", + Enabled: true, + Name: "updated.com", LogpullOptions: "fields=RayID,ClientIP,EdgeStartTimestamp", DestinationConf: "gs://mybucket/logs", } @@ -32,7 +33,7 @@ func ExampleAPI_CreateLogpushJob() { log.Fatal(err) } - job, err := api.CreateLogpushJob(zoneID, exampleNewLogpushJob) + job, err := api.CreateLogpushJob(context.TODO(), zoneID, exampleNewLogpushJob) if err != nil { log.Fatal(err) } @@ -51,7 +52,7 @@ func ExampleAPI_UpdateLogpushJob() { log.Fatal(err) } - err = api.UpdateLogpushJob(zoneID, 1, exampleUpdatedLogpushJob) + err = api.UpdateLogpushJob(context.TODO(), zoneID, 1, exampleUpdatedLogpushJob) if err != nil { log.Fatal(err) } @@ -68,7 +69,7 @@ func ExampleAPI_LogpushJobs() { log.Fatal(err) } - jobs, err := api.LogpushJobs(zoneID) + jobs, err := api.LogpushJobs(context.TODO(), zoneID) if err != nil { log.Fatal(err) } @@ -90,7 +91,7 @@ func ExampleAPI_LogpushJob() { log.Fatal(err) } - job, err := api.LogpushJob(zoneID, 1) + job, err := api.LogpushJob(context.TODO(), zoneID, 1) if err != nil { log.Fatal(err) } @@ -109,7 +110,7 @@ func ExampleAPI_DeleteLogpushJob() { log.Fatal(err) } - err = api.DeleteLogpushJob(zoneID, 1) + err = api.DeleteLogpushJob(context.TODO(), zoneID, 1) if err != nil { log.Fatal(err) } @@ -126,7 +127,7 @@ func ExampleAPI_GetLogpushOwnershipChallenge() { log.Fatal(err) } - ownershipChallenge, err := api.GetLogpushOwnershipChallenge(zoneID, "destination_conf") + ownershipChallenge, err := api.GetLogpushOwnershipChallenge(context.TODO(), zoneID, "destination_conf") if err != nil { log.Fatal(err) } @@ -145,7 +146,7 @@ func ExampleAPI_ValidateLogpushOwnershipChallenge() { log.Fatal(err) } - isValid, err := api.ValidateLogpushOwnershipChallenge(zoneID, "destination_conf", "ownership_challenge") + isValid, err := api.ValidateLogpushOwnershipChallenge(context.TODO(), zoneID, "destination_conf", "ownership_challenge") if err != nil { log.Fatal(err) } @@ -164,7 +165,7 @@ func ExampleAPI_CheckLogpushDestinationExists() { log.Fatal(err) } - exists, err := api.CheckLogpushDestinationExists(zoneID, "destination_conf") + exists, err := api.CheckLogpushDestinationExists(context.TODO(), zoneID, "destination_conf") if err != nil { log.Fatal(err) } diff --git a/logpush_test.go b/logpush_test.go index f56fe9ca61c..d7182008758 100644 --- a/logpush_test.go +++ b/logpush_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "strconv" @@ -80,7 +81,7 @@ func TestLogpushJobs(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -102,7 +103,7 @@ func TestLogpushJobs(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/jobs", handler) want := []LogpushJob{expectedLogpushJobStruct} - actual, err := client.LogpushJobs(testZoneID) + actual, err := client.LogpushJobs(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -113,7 +114,7 @@ func TestGetLogpushJob(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -127,7 +128,7 @@ func TestGetLogpushJob(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/jobs/"+strconv.Itoa(jobID), handler) want := expectedLogpushJobStruct - actual, err := client.LogpushJob(testZoneID, jobID) + actual, err := client.LogpushJob(context.TODO(), testZoneID, jobID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -144,7 +145,7 @@ func TestCreateLogpushJob(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -158,7 +159,7 @@ func TestCreateLogpushJob(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/jobs", handler) want := &expectedLogpushJobStruct - actual, err := client.CreateLogpushJob(testZoneID, newJob) + actual, err := client.CreateLogpushJob(context.TODO(), testZoneID, newJob) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -175,7 +176,7 @@ func TestUpdateLogpushJob(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -188,7 +189,7 @@ func TestUpdateLogpushJob(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/jobs/"+strconv.Itoa(jobID), handler) - err := client.UpdateLogpushJob(testZoneID, jobID, updatedJob) + err := client.UpdateLogpushJob(context.TODO(), testZoneID, jobID, updatedJob) assert.NoError(t, err) } @@ -197,7 +198,7 @@ func TestDeleteLogpushJob(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": null, @@ -210,7 +211,7 @@ func TestDeleteLogpushJob(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/jobs/"+strconv.Itoa(jobID), handler) - err := client.DeleteLogpushJob(testZoneID, jobID) + err := client.DeleteLogpushJob(context.TODO(), testZoneID, jobID) assert.NoError(t, err) } @@ -219,7 +220,7 @@ func TestGetLogpushOwnershipChallenge(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -234,7 +235,7 @@ func TestGetLogpushOwnershipChallenge(t *testing.T) { want := &expectedLogpushGetOwnershipChallengeStruct - actual, err := client.GetLogpushOwnershipChallenge(testZoneID, "destination_conf") + actual, err := client.GetLogpushOwnershipChallenge(context.TODO(), testZoneID, "destination_conf") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -245,7 +246,7 @@ func TestGetLogpushOwnershipChallengeWithInvalidResponse(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -257,7 +258,7 @@ func TestGetLogpushOwnershipChallengeWithInvalidResponse(t *testing.T) { } mux.HandleFunc("/zones/"+testZoneID+"/logpush/ownership", handler) - _, err := client.GetLogpushOwnershipChallenge(testZoneID, "destination_conf") + _, err := client.GetLogpushOwnershipChallenge(context.TODO(), testZoneID, "destination_conf") assert.Error(t, err) } @@ -280,7 +281,7 @@ func TestValidateLogpushOwnershipChallenge(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -295,7 +296,7 @@ func TestValidateLogpushOwnershipChallenge(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/ownership/validate", handler) - actual, err := client.ValidateLogpushOwnershipChallenge(testZoneID, "destination_conf", "ownership_challenge") + actual, err := client.ValidateLogpushOwnershipChallenge(context.TODO(), testZoneID, "destination_conf", "ownership_challenge") if assert.NoError(t, err) { assert.Equal(t, tc.isValid, actual) } @@ -321,7 +322,7 @@ func TestCheckLogpushDestinationExists(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -336,7 +337,7 @@ func TestCheckLogpushDestinationExists(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/logpush/validate/destination/exists", handler) - actual, err := client.CheckLogpushDestinationExists(testZoneID, "destination_conf") + actual, err := client.CheckLogpushDestinationExists(context.TODO(), testZoneID, "destination_conf") if assert.NoError(t, err) { assert.Equal(t, tc.exists, actual) } diff --git a/magic_firewall_rulesets_test.go b/magic_firewall_rulesets_test.go index b437eb33278..b494a5a173c 100644 --- a/magic_firewall_rulesets_test.go +++ b/magic_firewall_rulesets_test.go @@ -15,7 +15,7 @@ func TestListMagicFirewallRulesets(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": [ @@ -62,7 +62,7 @@ func TestGetMagicFirewallRuleset(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -134,7 +134,7 @@ func TestCreateMagicFirewallRuleset(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -206,7 +206,7 @@ func TestUpdateMagicFirewallRuleset(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -306,7 +306,7 @@ func TestDeleteMagicFirewallRuleset(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, ``) } diff --git a/origin_ca.go b/origin_ca.go index dde1803bba0..efebde2e729 100644 --- a/origin_ca.go +++ b/origin_ca.go @@ -3,6 +3,7 @@ package cloudflare import ( "context" "encoding/json" + "net/http" "net/url" "time" @@ -89,9 +90,9 @@ type originCACertificateResponseRevoke struct { // This function requires api.APIUserServiceKey be set to your Certificates API key. // // API reference: https://api.cloudflare.com/#cloudflare-ca-create-certificate -func (api *API) CreateOriginCertificate(certificate OriginCACertificate) (*OriginCACertificate, error) { +func (api *API) CreateOriginCertificate(ctx context.Context, certificate OriginCACertificate) (*OriginCACertificate, error) { uri := "/certificates" - res, err := api.makeRequestWithAuthType(context.TODO(), "POST", uri, certificate, AuthUserService) + res, err := api.makeRequestWithAuthType(ctx, http.MethodPost, uri, certificate, AuthUserService) if err != nil { return nil, err @@ -117,13 +118,13 @@ func (api *API) CreateOriginCertificate(certificate OriginCACertificate) (*Origi // This function requires api.APIUserServiceKey be set to your Certificates API key. // // API reference: https://api.cloudflare.com/#cloudflare-ca-list-certificates -func (api *API) OriginCertificates(options OriginCACertificateListOptions) ([]OriginCACertificate, error) { +func (api *API) OriginCertificates(ctx context.Context, options OriginCACertificateListOptions) ([]OriginCACertificate, error) { v := url.Values{} if options.ZoneID != "" { v.Set("zone_id", options.ZoneID) } uri := "/certificates" + "?" + v.Encode() - res, err := api.makeRequestWithAuthType(context.TODO(), "GET", uri, nil, AuthUserService) + res, err := api.makeRequestWithAuthType(ctx, http.MethodGet, uri, nil, AuthUserService) if err != nil { return nil, err @@ -149,9 +150,9 @@ func (api *API) OriginCertificates(options OriginCACertificateListOptions) ([]Or // This function requires api.APIUserServiceKey be set to your Certificates API key. // // API reference: https://api.cloudflare.com/#cloudflare-ca-certificate-details -func (api *API) OriginCertificate(certificateID string) (*OriginCACertificate, error) { +func (api *API) OriginCertificate(ctx context.Context, certificateID string) (*OriginCACertificate, error) { uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType(context.TODO(), "GET", uri, nil, AuthUserService) + res, err := api.makeRequestWithAuthType(ctx, http.MethodGet, uri, nil, AuthUserService) if err != nil { return nil, err @@ -177,9 +178,9 @@ func (api *API) OriginCertificate(certificateID string) (*OriginCACertificate, e // This function requires api.APIUserServiceKey be set to your Certificates API key. // // API reference: https://api.cloudflare.com/#cloudflare-ca-revoke-certificate -func (api *API) RevokeOriginCertificate(certificateID string) (*OriginCACertificateID, error) { +func (api *API) RevokeOriginCertificate(ctx context.Context, certificateID string) (*OriginCACertificateID, error) { uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType(context.TODO(), "DELETE", uri, nil, AuthUserService) + res, err := api.makeRequestWithAuthType(ctx, http.MethodDelete, uri, nil, AuthUserService) if err != nil { return nil, err diff --git a/origin_ca_test.go b/origin_ca_test.go index 6ad11ea4c9a..ca0256f931a 100644 --- a/origin_ca_test.go +++ b/origin_ca_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "encoding/json" "fmt" "net/http" @@ -49,7 +50,7 @@ func TestOriginCA_CreateOriginCertificate(t *testing.T) { defer teardown() mux.HandleFunc("/certificates", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %ss", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %ss", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -82,7 +83,7 @@ func TestOriginCA_CreateOriginCertificate(t *testing.T) { CSR: "-----BEGIN CERTIFICATE REQUEST-----MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxDzANBgNVBAcMBkxpbmRvbjEWMBQGA1UECgwNRGlnaUNlcnQgSW5jLjERMA8GA1UECwwIRGlnaUNlcnQxHTAbBgNVBAMMFGV4YW1wbGUuZGlnaWNlcnQuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8+To7d+2kPWeBv/orU3LVbJwDrSQbeKamCmowp5bqDxIwV20zqRb7APUOKYoVEFFOEQs6T6gImnIolhbiH6m4zgZ/CPvWBOkZc+c1Po2EmvBz+AD5sBdT5kzGQA6NbWyZGldxRthNLOs1efOhdnWFuhI162qmcflgpiIWDuwq4C9f+YkeJhNn9dF5+owm8cOQmDrV8NNdiTqin8q3qYAHHJRW28glJUCZkTZwIaSR6crBQ8TbYNE0dc+Caa3DOIkz1EOsHWzTx+n0zKfqcbgXi4DJx+C1bjptYPRBPZL8DAeWuA8ebudVT44yEp82G96/Ggcf7F33xMxe0yc+Xa6owIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEBAB0kcrFccSmFDmxox0Ne01UIqSsDqHgL+XmHTXJwre6DhJSZwbvEtOK0G3+dr4Fs11WuUNt5qcLsx5a8uk4G6AKHMzuhLsJ7XZjgmQXGECpYQ4mC3yT3ZoCGpIXbw+iP3lmEEXgaQL0Tx5LFl/okKbKYwIqNiyKWOMj7ZR/wxWg/ZDGRs55xuoeLDJ/ZRFf9bI+IaCUd1YrfYcHIl3G87Av+r49YVwqRDT0VDV7uLgqn29XI1PpVUNCPQGn9p/eX6Qo7vpDaPybRtA2R7XLKjQaF9oXWeCUqy1hvJac9QFO297Ob1alpHPoZ7mWiEuJwjBPii6a9M9G30nUo39lBi1w=-----END CERTIFICATE REQUEST-----", } - createdCertificate, err := client.CreateOriginCertificate(testCertificate) + createdCertificate, err := client.CreateOriginCertificate(context.TODO(), testCertificate) if assert.NoError(t, err) { assert.Equal(t, createdCertificate, &testCertificate) @@ -96,7 +97,7 @@ func TestOriginCA_OriginCertificates(t *testing.T) { testZoneID := "023e105f4ecef8ad9ca31a8372d0c353" mux.HandleFunc("/certificates", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %ss", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %ss", r.Method) assert.Equal(t, testZoneID, r.URL.Query().Get("zone_id"), "Expected zone_id '', got %%s", testZoneID) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -138,7 +139,7 @@ func TestOriginCA_OriginCertificates(t *testing.T) { CSR: "-----BEGIN CERTIFICATE REQUEST-----MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxDzANBgNVBAcMBkxpbmRvbjEWMBQGA1UECgwNRGlnaUNlcnQgSW5jLjERMA8GA1UECwwIRGlnaUNlcnQxHTAbBgNVBAMMFGV4YW1wbGUuZGlnaWNlcnQuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8+To7d+2kPWeBv/orU3LVbJwDrSQbeKamCmowp5bqDxIwV20zqRb7APUOKYoVEFFOEQs6T6gImnIolhbiH6m4zgZ/CPvWBOkZc+c1Po2EmvBz+AD5sBdT5kzGQA6NbWyZGldxRthNLOs1efOhdnWFuhI162qmcflgpiIWDuwq4C9f+YkeJhNn9dF5+owm8cOQmDrV8NNdiTqin8q3qYAHHJRW28glJUCZkTZwIaSR6crBQ8TbYNE0dc+Caa3DOIkz1EOsHWzTx+n0zKfqcbgXi4DJx+C1bjptYPRBPZL8DAeWuA8ebudVT44yEp82G96/Ggcf7F33xMxe0yc+Xa6owIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEBAB0kcrFccSmFDmxox0Ne01UIqSsDqHgL+XmHTXJwre6DhJSZwbvEtOK0G3+dr4Fs11WuUNt5qcLsx5a8uk4G6AKHMzuhLsJ7XZjgmQXGECpYQ4mC3yT3ZoCGpIXbw+iP3lmEEXgaQL0Tx5LFl/okKbKYwIqNiyKWOMj7ZR/wxWg/ZDGRs55xuoeLDJ/ZRFf9bI+IaCUd1YrfYcHIl3G87Av+r49YVwqRDT0VDV7uLgqn29XI1PpVUNCPQGn9p/eX6Qo7vpDaPybRtA2R7XLKjQaF9oXWeCUqy1hvJac9QFO297Ob1alpHPoZ7mWiEuJwjBPii6a9M9G30nUo39lBi1w=-----END CERTIFICATE REQUEST-----", } - certs, err := client.OriginCertificates(OriginCACertificateListOptions{ZoneID: testZoneID}) + certs, err := client.OriginCertificates(context.TODO(), OriginCACertificateListOptions{ZoneID: testZoneID}) if assert.NoError(t, err) { assert.IsType(t, []OriginCACertificate{}, certs, "Expected type []OriginCACertificate and got %v", certs) @@ -151,7 +152,7 @@ func TestOriginCA_OriginCertificate(t *testing.T) { defer teardown() mux.HandleFunc("/certificates/0x47530d8f561faa08", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %ss", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %ss", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -187,7 +188,7 @@ func TestOriginCA_OriginCertificate(t *testing.T) { CSR: "-----BEGIN CERTIFICATE REQUEST-----MIICvDCCAaQCAQAwdzELMAkGA1UEBhMCVVMxDTALBgNVBAgMBFV0YWgxDzANBgNVBAcMBkxpbmRvbjEWMBQGA1UECgwNRGlnaUNlcnQgSW5jLjERMA8GA1UECwwIRGlnaUNlcnQxHTAbBgNVBAMMFGV4YW1wbGUuZGlnaWNlcnQuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA8+To7d+2kPWeBv/orU3LVbJwDrSQbeKamCmowp5bqDxIwV20zqRb7APUOKYoVEFFOEQs6T6gImnIolhbiH6m4zgZ/CPvWBOkZc+c1Po2EmvBz+AD5sBdT5kzGQA6NbWyZGldxRthNLOs1efOhdnWFuhI162qmcflgpiIWDuwq4C9f+YkeJhNn9dF5+owm8cOQmDrV8NNdiTqin8q3qYAHHJRW28glJUCZkTZwIaSR6crBQ8TbYNE0dc+Caa3DOIkz1EOsHWzTx+n0zKfqcbgXi4DJx+C1bjptYPRBPZL8DAeWuA8ebudVT44yEp82G96/Ggcf7F33xMxe0yc+Xa6owIDAQABoAAwDQYJKoZIhvcNAQEFBQADggEBAB0kcrFccSmFDmxox0Ne01UIqSsDqHgL+XmHTXJwre6DhJSZwbvEtOK0G3+dr4Fs11WuUNt5qcLsx5a8uk4G6AKHMzuhLsJ7XZjgmQXGECpYQ4mC3yT3ZoCGpIXbw+iP3lmEEXgaQL0Tx5LFl/okKbKYwIqNiyKWOMj7ZR/wxWg/ZDGRs55xuoeLDJ/ZRFf9bI+IaCUd1YrfYcHIl3G87Av+r49YVwqRDT0VDV7uLgqn29XI1PpVUNCPQGn9p/eX6Qo7vpDaPybRtA2R7XLKjQaF9oXWeCUqy1hvJac9QFO297Ob1alpHPoZ7mWiEuJwjBPii6a9M9G30nUo39lBi1w=-----END CERTIFICATE REQUEST-----", } - cert, err := client.OriginCertificate(testCertificate.ID) + cert, err := client.OriginCertificate(context.TODO(), testCertificate.ID) if assert.NoError(t, err) { assert.IsType(t, &OriginCACertificate{}, cert, "Expected type &OriginCACertificate and got %v", cert) @@ -200,7 +201,7 @@ func TestOriginCA_RevokeCertificate(t *testing.T) { defer teardown() mux.HandleFunc("/certificates/0x47530d8f561faa08", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %ss", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %ss", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -216,7 +217,7 @@ func TestOriginCA_RevokeCertificate(t *testing.T) { ID: "0x47530d8f561faa08", } - cert, err := client.RevokeOriginCertificate(testCertificate.ID) + cert, err := client.RevokeOriginCertificate(context.TODO(), testCertificate.ID) if assert.NoError(t, err) { assert.IsType(t, &OriginCACertificateID{}, cert, "Expected type &OriginCACertificateID and got %v", cert) diff --git a/page_rules.go b/page_rules.go index 63d0a5de577..a43b5ec507f 100644 --- a/page_rules.go +++ b/page_rules.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -135,9 +137,9 @@ type PageRulesResponse struct { // CreatePageRule creates a new Page Rule for a zone. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-create-a-page-rule -func (api *API) CreatePageRule(zoneID string, rule PageRule) (*PageRule, error) { +func (api *API) CreatePageRule(ctx context.Context, zoneID string, rule PageRule) (*PageRule, error) { uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("POST", uri, rule) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, rule) if err != nil { return nil, err } @@ -152,9 +154,9 @@ func (api *API) CreatePageRule(zoneID string, rule PageRule) (*PageRule, error) // ListPageRules returns all Page Rules for a zone. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-list-page-rules -func (api *API) ListPageRules(zoneID string) ([]PageRule, error) { +func (api *API) ListPageRules(ctx context.Context, zoneID string) ([]PageRule, error) { uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []PageRule{}, err } @@ -169,9 +171,9 @@ func (api *API) ListPageRules(zoneID string) ([]PageRule, error) { // PageRule fetches detail about one Page Rule for a zone. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-page-rule-details -func (api *API) PageRule(zoneID, ruleID string) (PageRule, error) { +func (api *API) PageRule(ctx context.Context, zoneID, ruleID string) (PageRule, error) { uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return PageRule{}, err } @@ -187,9 +189,9 @@ func (api *API) PageRule(zoneID, ruleID string) (PageRule, error) { // in contrast to UpdatePageRule which replaces the entire Page Rule. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-change-a-page-rule -func (api *API) ChangePageRule(zoneID, ruleID string, rule PageRule) error { +func (api *API) ChangePageRule(ctx context.Context, zoneID, ruleID string, rule PageRule) error { uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PATCH", uri, rule) + res, err := api.makeRequestContext(ctx, "PATCH", uri, rule) if err != nil { return err } @@ -205,9 +207,9 @@ func (api *API) ChangePageRule(zoneID, ruleID string, rule PageRule) error { // ChangePageRule which lets you change individual settings. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-update-a-page-rule -func (api *API) UpdatePageRule(zoneID, ruleID string, rule PageRule) error { +func (api *API) UpdatePageRule(ctx context.Context, zoneID, ruleID string, rule PageRule) error { uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PUT", uri, rule) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, rule) if err != nil { return err } @@ -222,9 +224,9 @@ func (api *API) UpdatePageRule(zoneID, ruleID string, rule PageRule) error { // DeletePageRule deletes a Page Rule for a zone. // // API reference: https://api.cloudflare.com/#page-rules-for-a-zone-delete-a-page-rule -func (api *API) DeletePageRule(zoneID, ruleID string) error { +func (api *API) DeletePageRule(ctx context.Context, zoneID, ruleID string) error { uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/page_rules_example_test.go b/page_rules_example_test.go index 50b3de717ac..08a60dc34af 100644 --- a/page_rules_example_test.go +++ b/page_rules_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -42,7 +43,7 @@ func ExampleAPI_CreatePageRule() { log.Fatal(err) } - pageRule, err := api.CreatePageRule(zoneID, exampleNewPageRule) + pageRule, err := api.CreatePageRule(context.TODO(), zoneID, exampleNewPageRule) if err != nil { log.Fatal(err) } @@ -61,7 +62,7 @@ func ExampleAPI_ListPageRules() { log.Fatal(err) } - pageRules, err := api.ListPageRules(zoneID) + pageRules, err := api.ListPageRules(context.TODO(), zoneID) if err != nil { log.Fatal(err) } @@ -83,7 +84,7 @@ func ExampleAPI_PageRule() { log.Fatal(err) } - pageRules, err := api.PageRule(zoneID, "my_page_rule_id") + pageRules, err := api.PageRule(context.TODO(), zoneID, "my_page_rule_id") if err != nil { log.Fatal(err) } @@ -102,7 +103,7 @@ func ExampleAPI_DeletePageRule() { log.Fatal(err) } - err = api.DeletePageRule(zoneID, "my_page_rule_id") + err = api.DeletePageRule(context.TODO(), zoneID, "my_page_rule_id") if err != nil { log.Fatal(err) } diff --git a/page_rules_test.go b/page_rules_test.go index 4d197f20191..79bbb494ae8 100644 --- a/page_rules_test.go +++ b/page_rules_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -74,7 +75,7 @@ func TestListPageRules(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -96,7 +97,7 @@ func TestListPageRules(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/pagerules", handler) want := []PageRule{expectedPageRuleStruct} - actual, err := client.ListPageRules(testZoneID) + actual, err := client.ListPageRules(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -107,7 +108,7 @@ func TestGetPageRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -121,7 +122,7 @@ func TestGetPageRule(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/pagerules/"+pageRuleID, handler) want := expectedPageRuleStruct - actual, err := client.PageRule(testZoneID, pageRuleID) + actual, err := client.PageRule(context.TODO(), testZoneID, pageRuleID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -155,7 +156,7 @@ func TestCreatePageRule(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -169,7 +170,7 @@ func TestCreatePageRule(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/pagerules", handler) want := &expectedPageRuleStruct - actual, err := client.CreatePageRule(testZoneID, newPageRule) + actual, err := client.CreatePageRule(context.TODO(), testZoneID, newPageRule) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -180,7 +181,7 @@ func TestDeletePageRule(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": null, @@ -193,6 +194,6 @@ func TestDeletePageRule(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/pagerules/"+pageRuleID, handler) - err := client.DeletePageRule(testZoneID, pageRuleID) + err := client.DeletePageRule(context.TODO(), testZoneID, pageRuleID) assert.NoError(t, err) } diff --git a/railgun.go b/railgun.go index 8102c1ea343..396fc58d8ff 100644 --- a/railgun.go +++ b/railgun.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "time" @@ -48,14 +50,14 @@ type railgunsResponse struct { // CreateRailgun creates a new Railgun. // // API reference: https://api.cloudflare.com/#railgun-create-railgun -func (api *API) CreateRailgun(name string) (Railgun, error) { +func (api *API) CreateRailgun(ctx context.Context, name string) (Railgun, error) { uri := api.userBaseURL("") + "/railguns" params := struct { Name string `json:"name"` }{ Name: name, } - res, err := api.makeRequest("POST", uri, params) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params) if err != nil { return Railgun{}, err } @@ -69,13 +71,13 @@ func (api *API) CreateRailgun(name string) (Railgun, error) { // ListRailguns lists Railguns connected to an account. // // API reference: https://api.cloudflare.com/#railgun-list-railguns -func (api *API) ListRailguns(options RailgunListOptions) ([]Railgun, error) { +func (api *API) ListRailguns(ctx context.Context, options RailgunListOptions) ([]Railgun, error) { v := url.Values{} if options.Direction != "" { v.Set("direction", options.Direction) } uri := api.userBaseURL("") + "/railguns" + "?" + v.Encode() - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -89,9 +91,9 @@ func (api *API) ListRailguns(options RailgunListOptions) ([]Railgun, error) { // RailgunDetails returns the details for a Railgun. // // API reference: https://api.cloudflare.com/#railgun-railgun-details -func (api *API) RailgunDetails(railgunID string) (Railgun, error) { +func (api *API) RailgunDetails(ctx context.Context, railgunID string) (Railgun, error) { uri := api.userBaseURL("") + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return Railgun{}, err } @@ -105,9 +107,9 @@ func (api *API) RailgunDetails(railgunID string) (Railgun, error) { // RailgunZones returns the zones that are currently using a Railgun. // // API reference: https://api.cloudflare.com/#railgun-get-zones-connected-to-a-railgun -func (api *API) RailgunZones(railgunID string) ([]Zone, error) { +func (api *API) RailgunZones(ctx context.Context, railgunID string) ([]Zone, error) { uri := api.userBaseURL("") + "/railguns/" + railgunID + "/zones" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -121,14 +123,14 @@ func (api *API) RailgunZones(railgunID string) ([]Zone, error) { // enableRailgun enables (true) or disables (false) a Railgun for all zones connected to it. // // API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) enableRailgun(railgunID string, enable bool) (Railgun, error) { +func (api *API) enableRailgun(ctx context.Context, railgunID string, enable bool) (Railgun, error) { uri := api.userBaseURL("") + "/railguns/" + railgunID params := struct { Enabled bool `json:"enabled"` }{ Enabled: enable, } - res, err := api.makeRequest("PATCH", uri, params) + res, err := api.makeRequestContext(ctx, "PATCH", uri, params) if err != nil { return Railgun{}, err } @@ -142,23 +144,23 @@ func (api *API) enableRailgun(railgunID string, enable bool) (Railgun, error) { // EnableRailgun enables a Railgun for all zones connected to it. // // API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) EnableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, true) +func (api *API) EnableRailgun(ctx context.Context, railgunID string) (Railgun, error) { + return api.enableRailgun(ctx, railgunID, true) } // DisableRailgun enables a Railgun for all zones connected to it. // // API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) DisableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, false) +func (api *API) DisableRailgun(ctx context.Context, railgunID string) (Railgun, error) { + return api.enableRailgun(ctx, railgunID, false) } // DeleteRailgun disables and deletes a Railgun. // // API reference: https://api.cloudflare.com/#railgun-delete-railgun -func (api *API) DeleteRailgun(railgunID string) error { +func (api *API) DeleteRailgun(ctx context.Context, railgunID string) error { uri := api.userBaseURL("") + "/railguns/" + railgunID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { + if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { return err } return nil @@ -216,9 +218,9 @@ type railgunDiagnosisResponse struct { // ZoneRailguns returns the available Railguns for a zone. // // API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-available-railguns -func (api *API) ZoneRailguns(zoneID string) ([]ZoneRailgun, error) { +func (api *API) ZoneRailguns(ctx context.Context, zoneID string) ([]ZoneRailgun, error) { uri := "/zones/" + zoneID + "/railguns" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -232,9 +234,9 @@ func (api *API) ZoneRailguns(zoneID string) ([]ZoneRailgun, error) { // ZoneRailgunDetails returns the configuration for a given Railgun. // // API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-railgun-details -func (api *API) ZoneRailgunDetails(zoneID, railgunID string) (ZoneRailgun, error) { +func (api *API) ZoneRailgunDetails(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { uri := "/zones/" + zoneID + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ZoneRailgun{}, err } @@ -248,9 +250,9 @@ func (api *API) ZoneRailgunDetails(zoneID, railgunID string) (ZoneRailgun, error // TestRailgunConnection tests a Railgun connection for a given zone. // // API reference: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection -func (api *API) TestRailgunConnection(zoneID, railgunID string) (RailgunDiagnosis, error) { +func (api *API) TestRailgunConnection(ctx context.Context, zoneID, railgunID string) (RailgunDiagnosis, error) { uri := "/zones/" + zoneID + "/railguns/" + railgunID + "/diagnose" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return RailgunDiagnosis{}, err } @@ -264,14 +266,14 @@ func (api *API) TestRailgunConnection(zoneID, railgunID string) (RailgunDiagnosi // connectZoneRailgun connects (true) or disconnects (false) a Railgun for a given zone. // // API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) connectZoneRailgun(zoneID, railgunID string, connect bool) (ZoneRailgun, error) { +func (api *API) connectZoneRailgun(ctx context.Context, zoneID, railgunID string, connect bool) (ZoneRailgun, error) { uri := "/zones/" + zoneID + "/railguns/" + railgunID params := struct { Connected bool `json:"connected"` }{ Connected: connect, } - res, err := api.makeRequest("PATCH", uri, params) + res, err := api.makeRequestContext(ctx, "PATCH", uri, params) if err != nil { return ZoneRailgun{}, err } @@ -285,13 +287,13 @@ func (api *API) connectZoneRailgun(zoneID, railgunID string, connect bool) (Zone // ConnectZoneRailgun connects a Railgun for a given zone. // // API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) ConnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, true) +func (api *API) ConnectZoneRailgun(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { + return api.connectZoneRailgun(ctx, zoneID, railgunID, true) } // DisconnectZoneRailgun disconnects a Railgun for a given zone. // // API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) DisconnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, false) +func (api *API) DisconnectZoneRailgun(ctx context.Context, zoneID, railgunID string) (ZoneRailgun, error) { + return api.connectZoneRailgun(ctx, zoneID, railgunID, false) } diff --git a/railgun_test.go b/railgun_test.go index d19005fb22e..77eca09f9c2 100644 --- a/railgun_test.go +++ b/railgun_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "io/ioutil" "net/http" @@ -15,7 +16,7 @@ func TestCreateRailgun(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -62,7 +63,7 @@ func TestCreateRailgun(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.CreateRailgun("My Railgun") + actual, err := client.CreateRailgun(context.TODO(), "My Railgun") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -73,7 +74,7 @@ func TestListRailguns(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -125,7 +126,7 @@ func TestListRailguns(t *testing.T) { }, } - actual, err := client.ListRailguns(RailgunListOptions{Direction: "desc"}) + actual, err := client.ListRailguns(context.TODO(), RailgunListOptions{Direction: "desc"}) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -136,7 +137,7 @@ func TestRailgunDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -178,12 +179,12 @@ func TestRailgunDetails(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.RailgunDetails("e928d310693a83094309acf9ead50448") + actual, err := client.RailgunDetails(context.TODO(), "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.RailgunDetails("bar") + _, err = client.RailgunDetails(context.TODO(), "bar") assert.Error(t, err) } @@ -192,7 +193,7 @@ func TestRailgunZones(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -238,12 +239,12 @@ func TestRailgunZones(t *testing.T) { }, } - actual, err := client.RailgunZones("e928d310693a83094309acf9ead50448") + actual, err := client.RailgunZones(context.TODO(), "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.RailgunZones("bar") + _, err = client.RailgunZones(context.TODO(), "bar") assert.Error(t, err) } @@ -299,12 +300,12 @@ func TestEnableRailgun(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.EnableRailgun("e928d310693a83094309acf9ead50448") + actual, err := client.EnableRailgun(context.TODO(), "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.EnableRailgun("bar") + _, err = client.EnableRailgun(context.TODO(), "bar") assert.Error(t, err) } @@ -360,12 +361,12 @@ func TestDisableRailgun(t *testing.T) { ModifiedOn: modifiedOn, } - actual, err := client.DisableRailgun("e928d310693a83094309acf9ead50448") + actual, err := client.DisableRailgun(context.TODO(), "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.DisableRailgun("bar") + _, err = client.DisableRailgun(context.TODO(), "bar") assert.Error(t, err) } @@ -374,7 +375,7 @@ func TestDeleteRailgun(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -387,8 +388,8 @@ func TestDeleteRailgun(t *testing.T) { } mux.HandleFunc("/railguns/e928d310693a83094309acf9ead50448", handler) - assert.NoError(t, client.DeleteRailgun("e928d310693a83094309acf9ead50448")) - assert.Error(t, client.DeleteRailgun("bar")) + assert.NoError(t, client.DeleteRailgun(context.TODO(), "e928d310693a83094309acf9ead50448")) + assert.Error(t, client.DeleteRailgun(context.TODO(), "bar")) } func TestZoneRailguns(t *testing.T) { @@ -396,7 +397,7 @@ func TestZoneRailguns(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -429,12 +430,12 @@ func TestZoneRailguns(t *testing.T) { }, } - actual, err := client.ZoneRailguns("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.ZoneRailguns(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.ZoneRailguns("bar") + _, err = client.ZoneRailguns(context.TODO(), "bar") assert.Error(t, err) } @@ -443,7 +444,7 @@ func TestZoneRailgunDetails(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -466,12 +467,12 @@ func TestZoneRailgunDetails(t *testing.T) { Connected: true, } - actual, err := client.ZoneRailgunDetails("023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") + actual, err := client.ZoneRailgunDetails(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.ZoneRailgunDetails("bar", "baz") + _, err = client.ZoneRailgunDetails(context.TODO(), "bar", "baz") assert.Error(t, err) } @@ -480,7 +481,7 @@ func TestTestRailgunConnection(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -509,7 +510,7 @@ func TestTestRailgunConnection(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/railguns/e928d310693a83094309acf9ead50448/diagnose", handler) want := RailgunDiagnosis{ - Method: "GET", + Method: http.MethodGet, HostName: "www.example.com", HTTPStatus: 200, Railgun: "on", @@ -527,12 +528,12 @@ func TestTestRailgunConnection(t *testing.T) { CFCacheStatus: "", } - actual, err := client.TestRailgunConnection("023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") + actual, err := client.TestRailgunConnection(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.TestRailgunConnection("bar", "baz") + _, err = client.TestRailgunConnection(context.TODO(), "bar", "baz") assert.Error(t, err) } @@ -569,12 +570,12 @@ func TestConnectRailgun(t *testing.T) { Connected: true, } - actual, err := client.ConnectZoneRailgun("023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") + actual, err := client.ConnectZoneRailgun(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.ConnectZoneRailgun("bar", "baz") + _, err = client.ConnectZoneRailgun(context.TODO(), "bar", "baz") assert.Error(t, err) } @@ -611,11 +612,11 @@ func TestDisconnectRailgun(t *testing.T) { Connected: false, } - actual, err := client.DisconnectZoneRailgun("023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") + actual, err := client.DisconnectZoneRailgun(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "e928d310693a83094309acf9ead50448") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.DisconnectZoneRailgun("bar", "baz") + _, err = client.DisconnectZoneRailgun(context.TODO(), "bar", "baz") assert.Error(t, err) } diff --git a/rate_limiting.go b/rate_limiting.go index c111583d64c..77ee6d6d925 100644 --- a/rate_limiting.go +++ b/rate_limiting.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" @@ -87,9 +89,9 @@ type rateLimitListResponse struct { // CreateRateLimit creates a new rate limit for a zone. // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-create-a-ratelimit -func (api *API) CreateRateLimit(zoneID string, limit RateLimit) (RateLimit, error) { +func (api *API) CreateRateLimit(ctx context.Context, zoneID string, limit RateLimit) (RateLimit, error) { uri := "/zones/" + zoneID + "/rate_limits" - res, err := api.makeRequest("POST", uri, limit) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, limit) if err != nil { return RateLimit{}, err } @@ -103,7 +105,7 @@ func (api *API) CreateRateLimit(zoneID string, limit RateLimit) (RateLimit, erro // ListRateLimits returns Rate Limits for a zone, paginated according to the provided options // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) { +func (api *API) ListRateLimits(ctx context.Context, zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) { v := url.Values{} if pageOpts.PerPage > 0 { v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) @@ -117,7 +119,7 @@ func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]Rat uri = uri + "?" + v.Encode() } - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []RateLimit{}, ResultInfo{}, err } @@ -133,7 +135,7 @@ func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]Rat // ListAllRateLimits returns all Rate Limits for a zone. // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) { +func (api *API) ListAllRateLimits(ctx context.Context, zoneID string) ([]RateLimit, error) { pageOpts := PaginationOptions{ PerPage: 100, // this is the max page size allowed Page: 1, @@ -141,7 +143,7 @@ func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) { allRateLimits := make([]RateLimit, 0) for { - rateLimits, resultInfo, err := api.ListRateLimits(zoneID, pageOpts) + rateLimits, resultInfo, err := api.ListRateLimits(ctx, zoneID, pageOpts) if err != nil { return []RateLimit{}, err } @@ -162,9 +164,9 @@ func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) { // RateLimit fetches detail about one Rate Limit for a zone. // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-rate-limit-details -func (api *API) RateLimit(zoneID, limitID string) (RateLimit, error) { +func (api *API) RateLimit(ctx context.Context, zoneID, limitID string) (RateLimit, error) { uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return RateLimit{}, err } @@ -179,9 +181,9 @@ func (api *API) RateLimit(zoneID, limitID string) (RateLimit, error) { // UpdateRateLimit lets you replace a Rate Limit for a zone. // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-update-rate-limit -func (api *API) UpdateRateLimit(zoneID, limitID string, limit RateLimit) (RateLimit, error) { +func (api *API) UpdateRateLimit(ctx context.Context, zoneID, limitID string, limit RateLimit) (RateLimit, error) { uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("PUT", uri, limit) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, limit) if err != nil { return RateLimit{}, err } @@ -195,9 +197,9 @@ func (api *API) UpdateRateLimit(zoneID, limitID string, limit RateLimit) (RateLi // DeleteRateLimit deletes a Rate Limit for a zone. // // API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-delete-rate-limit -func (api *API) DeleteRateLimit(zoneID, limitID string) error { +func (api *API) DeleteRateLimit(ctx context.Context, zoneID, limitID string) error { uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/rate_limiting_example_test.go b/rate_limiting_example_test.go index 52b1db5555c..76f5727b5f5 100644 --- a/rate_limiting_example_test.go +++ b/rate_limiting_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -36,7 +37,7 @@ func ExampleAPI_CreateRateLimit() { log.Fatal(err) } - rateLimit, err := api.CreateRateLimit(zoneID, exampleNewRateLimit) + rateLimit, err := api.CreateRateLimit(context.TODO(), zoneID, exampleNewRateLimit) if err != nil { log.Fatal(err) } @@ -59,7 +60,7 @@ func ExampleAPI_ListRateLimits() { PerPage: 5, Page: 1, } - rateLimits, _, err := api.ListRateLimits(zoneID, pageOpts) + rateLimits, _, err := api.ListRateLimits(context.TODO(), zoneID, pageOpts) if err != nil { log.Fatal(err) } @@ -81,7 +82,7 @@ func ExampleAPI_RateLimit() { log.Fatal(err) } - rateLimits, err := api.RateLimit(zoneID, "my_rate_limit_id") + rateLimits, err := api.RateLimit(context.TODO(), zoneID, "my_rate_limit_id") if err != nil { log.Fatal(err) } @@ -100,7 +101,7 @@ func ExampleAPI_DeleteRateLimit() { log.Fatal(err) } - err = api.DeleteRateLimit(zoneID, "my_rate_limit_id") + err = api.DeleteRateLimit(context.TODO(), zoneID, "my_rate_limit_id") if err != nil { log.Fatal(err) } diff --git a/rate_limiting_test.go b/rate_limiting_test.go index 50c9d099dcb..add4f0f40de 100644 --- a/rate_limiting_test.go +++ b/rate_limiting_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "strings" @@ -99,7 +100,7 @@ func TestListRateLimits(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -121,7 +122,7 @@ func TestListRateLimits(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits", handler) want := []RateLimit{expectedRateLimitStruct} - actual, _, err := client.ListRateLimits(testZoneID, PaginationOptions{}) + actual, _, err := client.ListRateLimits(context.TODO(), testZoneID, PaginationOptions{}) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -132,7 +133,7 @@ func TestListRateLimitsWithPageOpts(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [ @@ -157,7 +158,7 @@ func TestListRateLimitsWithPageOpts(t *testing.T) { pageOpts := PaginationOptions{ PerPage: 50, } - actual, _, err := client.ListRateLimits(testZoneID, pageOpts) + actual, _, err := client.ListRateLimits(context.TODO(), testZoneID, pageOpts) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -169,7 +170,7 @@ func TestListAllRateLimitsDoesPagination(t *testing.T) { oneHundredRateLimitRecords := strings.Repeat(serverRateLimitDescription+",", 99) + serverRateLimitDescription handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") if r.URL.Query().Get("page") == "1" { fmt.Fprintf(w, `{ @@ -213,7 +214,7 @@ func TestListAllRateLimitsDoesPagination(t *testing.T) { want[i] = expectedRateLimitStruct } - actual, err := client.ListAllRateLimits(testZoneID) + actual, err := client.ListAllRateLimits(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -224,7 +225,7 @@ func TestGetRateLimit(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -238,7 +239,7 @@ func TestGetRateLimit(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits/"+rateLimitID, handler) want := expectedRateLimitStruct - actual, err := client.RateLimit(testZoneID, rateLimitID) + actual, err := client.RateLimit(context.TODO(), testZoneID, rateLimitID) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -266,7 +267,7 @@ func TestCreateRateLimit(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -280,7 +281,7 @@ func TestCreateRateLimit(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits", handler) want := expectedRateLimitStruct - actual, err := client.CreateRateLimit(testZoneID, newRateLimit) + actual, err := client.CreateRateLimit(context.TODO(), testZoneID, newRateLimit) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -305,7 +306,7 @@ func TestCreateRateLimitWithZeroedThreshold(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.WriteHeader(400) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ @@ -319,7 +320,7 @@ func TestCreateRateLimitWithZeroedThreshold(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits", handler) - actual, err := client.CreateRateLimit(testZoneID, newRateLimit) + actual, err := client.CreateRateLimit(context.TODO(), testZoneID, newRateLimit) assert.Error(t, err) assert.Equal(t, RateLimit{}, actual) } @@ -343,7 +344,7 @@ func TestUpdateRateLimit(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": %s, @@ -357,7 +358,7 @@ func TestUpdateRateLimit(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits/"+rateLimitID, handler) want := expectedRateLimitStruct - actual, err := client.UpdateRateLimit(testZoneID, rateLimitID, newRateLimit) + actual, err := client.UpdateRateLimit(context.TODO(), testZoneID, rateLimitID, newRateLimit) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -368,7 +369,7 @@ func TestDeleteRateLimit(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": null, @@ -381,6 +382,6 @@ func TestDeleteRateLimit(t *testing.T) { mux.HandleFunc("/zones/"+testZoneID+"/rate_limits/"+rateLimitID, handler) - err := client.DeleteRateLimit(testZoneID, rateLimitID) + err := client.DeleteRateLimit(context.TODO(), testZoneID, rateLimitID) assert.NoError(t, err) } diff --git a/registrar.go b/registrar.go index 18cdf807e80..9641df9653b 100644 --- a/registrar.go +++ b/registrar.go @@ -1,8 +1,10 @@ package cloudflare import ( + "context" "encoding/json" "fmt" + "net/http" "time" "github.com/pkg/errors" @@ -80,10 +82,10 @@ type RegistrarDomainsDetailResponse struct { // domain name. // // API reference: https://api.cloudflare.com/#registrar-domains-get-domain -func (api *API) RegistrarDomain(accountID, domainName string) (RegistrarDomain, error) { +func (api *API) RegistrarDomain(ctx context.Context, accountID, domainName string) (RegistrarDomain, error) { uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s", accountID, domainName) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return RegistrarDomain{}, err } @@ -100,10 +102,10 @@ func (api *API) RegistrarDomain(accountID, domainName string) (RegistrarDomain, // ID. // // API reference: https://api.cloudflare.com/#registrar-domains-list-domains -func (api *API) RegistrarDomains(accountID string) ([]RegistrarDomain, error) { +func (api *API) RegistrarDomains(ctx context.Context, accountID string) ([]RegistrarDomain, error) { uri := "/accounts/" + accountID + "/registrar/domains" - res, err := api.makeRequest("POST", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) if err != nil { return []RegistrarDomain{}, err } @@ -120,10 +122,10 @@ func (api *API) RegistrarDomains(accountID string) ([]RegistrarDomain, error) { // to Cloudflare Registrar. // // API reference: https://api.cloudflare.com/#registrar-domains-transfer-domain -func (api *API) TransferRegistrarDomain(accountID, domainName string) ([]RegistrarDomain, error) { +func (api *API) TransferRegistrarDomain(ctx context.Context, accountID, domainName string) ([]RegistrarDomain, error) { uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s/transfer", accountID, domainName) - res, err := api.makeRequest("POST", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) if err != nil { return []RegistrarDomain{}, err } @@ -139,10 +141,10 @@ func (api *API) TransferRegistrarDomain(accountID, domainName string) ([]Registr // CancelRegistrarDomainTransfer cancels a pending domain transfer. // // API reference: https://api.cloudflare.com/#registrar-domains-cancel-transfer -func (api *API) CancelRegistrarDomainTransfer(accountID, domainName string) ([]RegistrarDomain, error) { +func (api *API) CancelRegistrarDomainTransfer(ctx context.Context, accountID, domainName string) ([]RegistrarDomain, error) { uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s/cancel_transfer", accountID, domainName) - res, err := api.makeRequest("POST", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, nil) if err != nil { return []RegistrarDomain{}, err } @@ -158,10 +160,10 @@ func (api *API) CancelRegistrarDomainTransfer(accountID, domainName string) ([]R // UpdateRegistrarDomain updates an existing Registrar Domain configuration. // // API reference: https://api.cloudflare.com/#registrar-domains-update-domain -func (api *API) UpdateRegistrarDomain(accountID, domainName string, domainConfiguration RegistrarDomainConfiguration) (RegistrarDomain, error) { +func (api *API) UpdateRegistrarDomain(ctx context.Context, accountID, domainName string, domainConfiguration RegistrarDomainConfiguration) (RegistrarDomain, error) { uri := fmt.Sprintf("/accounts/%s/registrar/domains/%s", accountID, domainName) - res, err := api.makeRequest("PUT", uri, domainConfiguration) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, domainConfiguration) if err != nil { return RegistrarDomain{}, err } @@ -172,4 +174,4 @@ func (api *API) UpdateRegistrarDomain(accountID, domainName string, domainConfig return RegistrarDomain{}, errors.Wrap(err, errUnmarshalError) } return r.Result, nil -} +} \ No newline at end of file diff --git a/registrar_example_test.go b/registrar_example_test.go index 15b5e518b3f..16ca0f71a25 100644 --- a/registrar_example_test.go +++ b/registrar_example_test.go @@ -1,113 +1,110 @@ -package cloudflare_test - -import ( - "fmt" - "log" - "time" - - cloudflare "github.com/cloudflare/cloudflare-go" -) - -var ( - createdAndModifiedTimestamp, _ = time.Parse(time.RFC3339, "2018-08-28T17:26:26Z") - expiresAtTimestamp, _ = time.Parse(time.RFC3339, "2019-08-28T23:59:59Z") - expectedRegistrarTransferIn = cloudflare.RegistrarTransferIn{ - UnlockDomain: "ok", - DisablePrivacy: "ok", - EnterAuthCode: "needed", - ApproveTransfer: "unknown", - AcceptFoa: "needed", - CanCancelTransfer: true, - } - expectedRegistrarContact = cloudflare.RegistrantContact{ - ID: "ea95132c15732412d22c1476fa83f27a", - FirstName: "John", - LastName: "Appleseed", - Organization: "Cloudflare, Inc.", - Address: "123 Sesame St.", - Address2: "Suite 430", - City: "Austin", - State: "TX", - Zip: "12345", - Country: "US", - Phone: "+1 123-123-1234", - Email: "user@example.com", - Fax: "123-867-5309", - } - expectedRegistrarDomain = cloudflare.RegistrarDomain{ - ID: "ea95132c15732412d22c1476fa83f27a", - Available: false, - SupportedTLD: true, - CanRegister: false, - TransferIn: expectedRegistrarTransferIn, - CurrentRegistrar: "Cloudflare", - ExpiresAt: expiresAtTimestamp, - RegistryStatuses: "ok,serverTransferProhibited", - Locked: false, - CreatedAt: createdAndModifiedTimestamp, - UpdatedAt: createdAndModifiedTimestamp, - RegistrantContact: expectedRegistrarContact, - } -) - -func ExampleAPI_RegistrarDomain() { - api, err := cloudflare.New(apiKey, user) - if err != nil { - log.Fatal(err) - } - - domain, err := api.RegistrarDomain("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - fmt.Printf("%+v\n", domain) -} - -func ExampleAPI_RegistrarDomains() { - api, err := cloudflare.New(apiKey, user) - if err != nil { - log.Fatal(err) - } - - domains, err := api.RegistrarDomains("01a7362d577a6c3019a474fd6f485823") - - fmt.Printf("%+v\n", domains) -} - -func ExampleAPI_TransferRegistrarDomain() { - api, err := cloudflare.New(apiKey, user) - if err != nil { - log.Fatal(err) - } - - domain, err := api.TransferRegistrarDomain("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - fmt.Printf("%+v\n", domain) -} - -func ExampleAPI_CancelRegistrarDomainTransfer() { - api, err := cloudflare.New(apiKey, user) - if err != nil { - log.Fatal(err) - } - - domains, err := api.CancelRegistrarDomainTransfer("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - fmt.Printf("%+v\n", domains) -} - -func ExampleAPI_UpdateRegistrarDomain() { - api, err := cloudflare.New(apiKey, user) - if err != nil { - log.Fatal(err) - } - - domain, err := api.UpdateRegistrarDomain( - "01a7362d577a6c3019a474fd6f485823", - "cloudflare.com", - cloudflare.RegistrarDomainConfiguration{ - NameServers: []string{"ns1.cloudflare.com", "ns2.cloudflare.com"}, - Locked: false, - }, - ) - - fmt.Printf("%+v\n", domain) -} +package cloudflare_test + +import ( + "context" + "fmt" + "log" + "time" + + cloudflare "github.com/cloudflare/cloudflare-go" +) + +var ( + createdAndModifiedTimestamp, _ = time.Parse(time.RFC3339, "2018-08-28T17:26:26Z") + expiresAtTimestamp, _ = time.Parse(time.RFC3339, "2019-08-28T23:59:59Z") + expectedRegistrarTransferIn = cloudflare.RegistrarTransferIn{ + UnlockDomain: "ok", + DisablePrivacy: "ok", + EnterAuthCode: "needed", + ApproveTransfer: "unknown", + AcceptFoa: "needed", + CanCancelTransfer: true, + } + expectedRegistrarContact = cloudflare.RegistrantContact{ + ID: "ea95132c15732412d22c1476fa83f27a", + FirstName: "John", + LastName: "Appleseed", + Organization: "Cloudflare, Inc.", + Address: "123 Sesame St.", + Address2: "Suite 430", + City: "Austin", + State: "TX", + Zip: "12345", + Country: "US", + Phone: "+1 123-123-1234", + Email: "user@example.com", + Fax: "123-867-5309", + } + expectedRegistrarDomain = cloudflare.RegistrarDomain{ + ID: "ea95132c15732412d22c1476fa83f27a", + Available: false, + SupportedTLD: true, + CanRegister: false, + TransferIn: expectedRegistrarTransferIn, + CurrentRegistrar: "Cloudflare", + ExpiresAt: expiresAtTimestamp, + RegistryStatuses: "ok,serverTransferProhibited", + Locked: false, + CreatedAt: createdAndModifiedTimestamp, + UpdatedAt: createdAndModifiedTimestamp, + RegistrantContact: expectedRegistrarContact, + } +) + +func ExampleAPI_RegistrarDomain() { + api, err := cloudflare.New(apiKey, user) + if err != nil { + log.Fatal(err) + } + + domain, err := api.RegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + fmt.Printf("%+v\n", domain) +} + +func ExampleAPI_RegistrarDomains() { + api, err := cloudflare.New(apiKey, user) + if err != nil { + log.Fatal(err) + } + + domains, err := api.RegistrarDomains(context.TODO(), "01a7362d577a6c3019a474fd6f485823") + + fmt.Printf("%+v\n", domains) +} + +func ExampleAPI_TransferRegistrarDomain() { + api, err := cloudflare.New(apiKey, user) + if err != nil { + log.Fatal(err) + } + + domain, err := api.TransferRegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + fmt.Printf("%+v\n", domain) +} + +func ExampleAPI_CancelRegistrarDomainTransfer() { + api, err := cloudflare.New(apiKey, user) + if err != nil { + log.Fatal(err) + } + + domains, err := api.CancelRegistrarDomainTransfer(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + fmt.Printf("%+v\n", domains) +} + +func ExampleAPI_UpdateRegistrarDomain() { + api, err := cloudflare.New(apiKey, user) + if err != nil { + log.Fatal(err) + } + + domain, err := api.UpdateRegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com", cloudflare.RegistrarDomainConfiguration{ + NameServers: []string{"ns1.cloudflare.com", "ns2.cloudflare.com"}, + Locked: false, + }) + + fmt.Printf("%+v\n", domain) +} diff --git a/registrar_test.go b/registrar_test.go index 54f452532f9..a74ddf3b2d7 100644 --- a/registrar_test.go +++ b/registrar_test.go @@ -1,417 +1,414 @@ -package cloudflare - -import ( - "fmt" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -const ( - registrarDomainPayload = `{ - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } -` -) - -var ( - createdAndModifiedTimestamp, _ = time.Parse(time.RFC3339, "2018-08-28T17:26:26Z") - expiresAtTimestamp, _ = time.Parse(time.RFC3339, "2019-08-28T23:59:59Z") - expectedRegistrarTransferIn = RegistrarTransferIn{ - UnlockDomain: "ok", - DisablePrivacy: "ok", - EnterAuthCode: "needed", - ApproveTransfer: "unknown", - AcceptFoa: "needed", - CanCancelTransfer: true, - } - expectedRegistrarContact = RegistrantContact{ - ID: "ea95132c15732412d22c1476fa83f27a", - FirstName: "John", - LastName: "Appleseed", - Organization: "Cloudflare, Inc.", - Address: "123 Sesame St.", - Address2: "Suite 430", - City: "Austin", - State: "TX", - Zip: "12345", - Country: "US", - Phone: "+1 123-123-1234", - Email: "user@example.com", - Fax: "123-867-5309", - } - expectedRegistrarDomain = RegistrarDomain{ - ID: "ea95132c15732412d22c1476fa83f27a", - Available: false, - SupportedTLD: true, - CanRegister: false, - TransferIn: expectedRegistrarTransferIn, - CurrentRegistrar: "Cloudflare", - ExpiresAt: expiresAtTimestamp, - RegistryStatuses: "ok,serverTransferProhibited", - Locked: false, - CreatedAt: createdAndModifiedTimestamp, - UpdatedAt: createdAndModifiedTimestamp, - RegistrantContact: expectedRegistrarContact, - } -) - -func TestRegistrarDomain(t *testing.T) { - setup() - defer teardown() - - handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) - w.Header().Set("content-type", "application/json") - fmt.Fprintf(w, `{ - "success": true, - "errors": [], - "messages": [], - "result": { - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } - } - `) - } - - mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com", handler) - - actual, err := client.RegistrarDomain("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - if assert.NoError(t, err) { - assert.Equal(t, expectedRegistrarDomain, actual) - } -} - -func TestRegistrarDomains(t *testing.T) { - setup() - defer teardown() - - handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) - w.Header().Set("content-type", "application/json") - fmt.Fprintf(w, `{ - "success": true, - "errors": [], - "messages": [], - "result": [ - { - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } - ], - "result_info": { - "page": 1, - "per_page": 20, - "count": 1, - "total_count": 2000 - } - } - `) - } - - mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains", handler) - - actual, err := client.RegistrarDomains("01a7362d577a6c3019a474fd6f485823") - - if assert.NoError(t, err) { - assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) - } -} - -func TestTransferRegistrarDomain(t *testing.T) { - setup() - defer teardown() - - handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) - w.Header().Set("content-type", "application/json") - fmt.Fprintf(w, `{ - "success": true, - "errors": [], - "messages": [], - "result": [ - { - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } - ], - "result_info": { - "page": 1, - "per_page": 20, - "count": 1, - "total_count": 2000 - } - } - `) - } - - mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com/transfer", handler) - - actual, err := client.TransferRegistrarDomain("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - if assert.NoError(t, err) { - assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) - } -} - -func TestCancelRegistrarDomainTransfer(t *testing.T) { - setup() - defer teardown() - - handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) - w.Header().Set("content-type", "application/json") - fmt.Fprintf(w, `{ - "success": true, - "errors": [], - "messages": [], - "result": [ - { - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } - ], - "result_info": { - "page": 1, - "per_page": 20, - "count": 1, - "total_count": 2000 - } - } - `) - } - - mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com/cancel_transfer", handler) - - actual, err := client.CancelRegistrarDomainTransfer("01a7362d577a6c3019a474fd6f485823", "cloudflare.com") - - if assert.NoError(t, err) { - assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) - } -} - -func TestUpdateRegistrarDomain(t *testing.T) { - setup() - defer teardown() - - handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) - w.Header().Set("content-type", "application/json") - fmt.Fprintf(w, `{ - "success": true, - "errors": [], - "messages": [], - "result": { - "id": "ea95132c15732412d22c1476fa83f27a", - "available": false, - "supported_tld": true, - "can_register": false, - "transfer_in": { - "unlock_domain": "ok", - "disable_privacy": "ok", - "enter_auth_code": "needed", - "approve_transfer": "unknown", - "accept_foa": "needed", - "can_cancel_transfer": true - }, - "current_registrar": "Cloudflare", - "expires_at": "2019-08-28T23:59:59Z", - "registry_statuses": "ok,serverTransferProhibited", - "locked": false, - "created_at": "2018-08-28T17:26:26Z", - "updated_at": "2018-08-28T17:26:26Z", - "registrant_contact": { - "id": "ea95132c15732412d22c1476fa83f27a", - "first_name": "John", - "last_name": "Appleseed", - "organization": "Cloudflare, Inc.", - "address": "123 Sesame St.", - "address2": "Suite 430", - "city": "Austin", - "state": "TX", - "zip": "12345", - "country": "US", - "phone": "+1 123-123-1234", - "email": "user@example.com", - "fax": "123-867-5309" - } - } - } - `) - } - - mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com", handler) - - actual, err := client.UpdateRegistrarDomain( - "01a7362d577a6c3019a474fd6f485823", - "cloudflare.com", - RegistrarDomainConfiguration{ - NameServers: []string{"ns1.cloudflare.com", "ns2.cloudflare.com"}, - Locked: false, - }, - ) - - if assert.NoError(t, err) { - assert.Equal(t, expectedRegistrarDomain, actual) - } -} +package cloudflare + +import ( + "context" + "fmt" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +const ( + registrarDomainPayload = `{ + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } +` +) + +var ( + createdAndModifiedTimestamp, _ = time.Parse(time.RFC3339, "2018-08-28T17:26:26Z") + expiresAtTimestamp, _ = time.Parse(time.RFC3339, "2019-08-28T23:59:59Z") + expectedRegistrarTransferIn = RegistrarTransferIn{ + UnlockDomain: "ok", + DisablePrivacy: "ok", + EnterAuthCode: "needed", + ApproveTransfer: "unknown", + AcceptFoa: "needed", + CanCancelTransfer: true, + } + expectedRegistrarContact = RegistrantContact{ + ID: "ea95132c15732412d22c1476fa83f27a", + FirstName: "John", + LastName: "Appleseed", + Organization: "Cloudflare, Inc.", + Address: "123 Sesame St.", + Address2: "Suite 430", + City: "Austin", + State: "TX", + Zip: "12345", + Country: "US", + Phone: "+1 123-123-1234", + Email: "user@example.com", + Fax: "123-867-5309", + } + expectedRegistrarDomain = RegistrarDomain{ + ID: "ea95132c15732412d22c1476fa83f27a", + Available: false, + SupportedTLD: true, + CanRegister: false, + TransferIn: expectedRegistrarTransferIn, + CurrentRegistrar: "Cloudflare", + ExpiresAt: expiresAtTimestamp, + RegistryStatuses: "ok,serverTransferProhibited", + Locked: false, + CreatedAt: createdAndModifiedTimestamp, + UpdatedAt: createdAndModifiedTimestamp, + RegistrantContact: expectedRegistrarContact, + } +) + +func TestRegistrarDomain(t *testing.T) { + setup() + defer teardown() + + handler := func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) + w.Header().Set("content-type", "application/json") + fmt.Fprintf(w, `{ + "success": true, + "errors": [], + "messages": [], + "result": { + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } + } + `) + } + + mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com", handler) + + actual, err := client.RegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + if assert.NoError(t, err) { + assert.Equal(t, expectedRegistrarDomain, actual) + } +} + +func TestRegistrarDomains(t *testing.T) { + setup() + defer teardown() + + handler := func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) + w.Header().Set("content-type", "application/json") + fmt.Fprintf(w, `{ + "success": true, + "errors": [], + "messages": [], + "result": [ + { + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } + ], + "result_info": { + "page": 1, + "per_page": 20, + "count": 1, + "total_count": 2000 + } + } + `) + } + + mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains", handler) + + actual, err := client.RegistrarDomains(context.TODO(), "01a7362d577a6c3019a474fd6f485823") + + if assert.NoError(t, err) { + assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) + } +} + +func TestTransferRegistrarDomain(t *testing.T) { + setup() + defer teardown() + + handler := func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) + w.Header().Set("content-type", "application/json") + fmt.Fprintf(w, `{ + "success": true, + "errors": [], + "messages": [], + "result": [ + { + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } + ], + "result_info": { + "page": 1, + "per_page": 20, + "count": 1, + "total_count": 2000 + } + } + `) + } + + mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com/transfer", handler) + + actual, err := client.TransferRegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + if assert.NoError(t, err) { + assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) + } +} + +func TestCancelRegistrarDomainTransfer(t *testing.T) { + setup() + defer teardown() + + handler := func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) + w.Header().Set("content-type", "application/json") + fmt.Fprintf(w, `{ + "success": true, + "errors": [], + "messages": [], + "result": [ + { + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } + ], + "result_info": { + "page": 1, + "per_page": 20, + "count": 1, + "total_count": 2000 + } + } + `) + } + + mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com/cancel_transfer", handler) + + actual, err := client.CancelRegistrarDomainTransfer(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com") + + if assert.NoError(t, err) { + assert.Equal(t, []RegistrarDomain{expectedRegistrarDomain}, actual) + } +} + +func TestUpdateRegistrarDomain(t *testing.T) { + setup() + defer teardown() + + handler := func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) + w.Header().Set("content-type", "application/json") + fmt.Fprintf(w, `{ + "success": true, + "errors": [], + "messages": [], + "result": { + "id": "ea95132c15732412d22c1476fa83f27a", + "available": false, + "supported_tld": true, + "can_register": false, + "transfer_in": { + "unlock_domain": "ok", + "disable_privacy": "ok", + "enter_auth_code": "needed", + "approve_transfer": "unknown", + "accept_foa": "needed", + "can_cancel_transfer": true + }, + "current_registrar": "Cloudflare", + "expires_at": "2019-08-28T23:59:59Z", + "registry_statuses": "ok,serverTransferProhibited", + "locked": false, + "created_at": "2018-08-28T17:26:26Z", + "updated_at": "2018-08-28T17:26:26Z", + "registrant_contact": { + "id": "ea95132c15732412d22c1476fa83f27a", + "first_name": "John", + "last_name": "Appleseed", + "organization": "Cloudflare, Inc.", + "address": "123 Sesame St.", + "address2": "Suite 430", + "city": "Austin", + "state": "TX", + "zip": "12345", + "country": "US", + "phone": "+1 123-123-1234", + "email": "user@example.com", + "fax": "123-867-5309" + } + } + } + `) + } + + mux.HandleFunc("/accounts/01a7362d577a6c3019a474fd6f485823/registrar/domains/cloudflare.com", handler) + + actual, err := client.UpdateRegistrarDomain(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "cloudflare.com", RegistrarDomainConfiguration{ + NameServers: []string{"ns1.cloudflare.com", "ns2.cloudflare.com"}, + Locked: false, + }) + + if assert.NoError(t, err) { + assert.Equal(t, expectedRegistrarDomain, actual) + } +} diff --git a/spectrum.go b/spectrum.go index 9267ca98d1d..f2bd8334d1b 100644 --- a/spectrum.go +++ b/spectrum.go @@ -1,9 +1,11 @@ package cloudflare import ( + "context" "encoding/json" "fmt" "net" + "net/http" "strconv" "strings" "time" @@ -262,10 +264,10 @@ func (c SpectrumApplicationConnectivity) Static() bool { // SpectrumApplications fetches all of the Spectrum applications for a zone. // // API reference: https://developers.cloudflare.com/spectrum/api-reference/#list-spectrum-applications -func (api *API) SpectrumApplications(zoneID string) ([]SpectrumApplication, error) { +func (api *API) SpectrumApplications(ctx context.Context, zoneID string) ([]SpectrumApplication, error) { uri := "/zones/" + zoneID + "/spectrum/apps" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []SpectrumApplication{}, err } @@ -282,14 +284,14 @@ func (api *API) SpectrumApplications(zoneID string) ([]SpectrumApplication, erro // SpectrumApplication fetches a single Spectrum application based on the ID. // // API reference: https://developers.cloudflare.com/spectrum/api-reference/#list-spectrum-applications -func (api *API) SpectrumApplication(zoneID string, applicationID string) (SpectrumApplication, error) { +func (api *API) SpectrumApplication(ctx context.Context, zoneID string, applicationID string) (SpectrumApplication, error) { uri := fmt.Sprintf( "/zones/%s/spectrum/apps/%s", zoneID, applicationID, ) - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return SpectrumApplication{}, err } @@ -306,10 +308,10 @@ func (api *API) SpectrumApplication(zoneID string, applicationID string) (Spectr // CreateSpectrumApplication creates a new Spectrum application. // // API reference: https://developers.cloudflare.com/spectrum/api-reference/#create-a-spectrum-application -func (api *API) CreateSpectrumApplication(zoneID string, appDetails SpectrumApplication) (SpectrumApplication, error) { +func (api *API) CreateSpectrumApplication(ctx context.Context, zoneID string, appDetails SpectrumApplication) (SpectrumApplication, error) { uri := "/zones/" + zoneID + "/spectrum/apps" - res, err := api.makeRequest("POST", uri, appDetails) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, appDetails) if err != nil { return SpectrumApplication{}, err } @@ -326,14 +328,14 @@ func (api *API) CreateSpectrumApplication(zoneID string, appDetails SpectrumAppl // UpdateSpectrumApplication updates an existing Spectrum application. // // API reference: https://developers.cloudflare.com/spectrum/api-reference/#update-a-spectrum-application -func (api *API) UpdateSpectrumApplication(zoneID, appID string, appDetails SpectrumApplication) (SpectrumApplication, error) { +func (api *API) UpdateSpectrumApplication(ctx context.Context, zoneID, appID string, appDetails SpectrumApplication) (SpectrumApplication, error) { uri := fmt.Sprintf( "/zones/%s/spectrum/apps/%s", zoneID, appID, ) - res, err := api.makeRequest("PUT", uri, appDetails) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, appDetails) if err != nil { return SpectrumApplication{}, err } @@ -350,14 +352,14 @@ func (api *API) UpdateSpectrumApplication(zoneID, appID string, appDetails Spect // DeleteSpectrumApplication removes a Spectrum application based on the ID. // // API reference: https://developers.cloudflare.com/spectrum/api-reference/#delete-a-spectrum-application -func (api *API) DeleteSpectrumApplication(zoneID string, applicationID string) error { +func (api *API) DeleteSpectrumApplication(ctx context.Context, zoneID string, applicationID string) error { uri := fmt.Sprintf( "/zones/%s/spectrum/apps/%s", zoneID, applicationID, ) - _, err := api.makeRequest("DELETE", uri, nil) + _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/spectrum_test.go b/spectrum_test.go index de9e74ca698..6407cb45e79 100644 --- a/spectrum_test.go +++ b/spectrum_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net" "net/http" @@ -15,7 +16,7 @@ func TestSpectrumApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -60,7 +61,7 @@ func TestSpectrumApplication(t *testing.T) { TLS: "off", } - actual, err := client.SpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") + actual, err := client.SpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -71,7 +72,7 @@ func TestSpectrumApplications(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": [ @@ -120,7 +121,7 @@ func TestSpectrumApplications(t *testing.T) { }, } - actual, err := client.SpectrumApplications("01a7362d577a6c3019a474fd6f485823") + actual, err := client.SpectrumApplications(context.TODO(), "01a7362d577a6c3019a474fd6f485823") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -131,7 +132,7 @@ func TestUpdateSpectrumApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -177,7 +178,7 @@ func TestUpdateSpectrumApplication(t *testing.T) { ModifiedOn: &modifiedOn, } - actual, err := client.UpdateSpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c", want) + actual, err := client.UpdateSpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -188,7 +189,7 @@ func TestCreateSpectrumApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -234,7 +235,7 @@ func TestCreateSpectrumApplication(t *testing.T) { ModifiedOn: &modifiedOn, } - actual, err := client.CreateSpectrumApplication("01a7362d577a6c3019a474fd6f485823", want) + actual, err := client.CreateSpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -245,7 +246,7 @@ func TestCreateSpectrumApplication_OriginDNS(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -297,7 +298,7 @@ func TestCreateSpectrumApplication_OriginDNS(t *testing.T) { ModifiedOn: &modifiedOn, } - actual, err := client.CreateSpectrumApplication("01a7362d577a6c3019a474fd6f485823", want) + actual, err := client.CreateSpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -308,7 +309,7 @@ func TestDeleteSpectrumApplication(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -322,7 +323,7 @@ func TestDeleteSpectrumApplication(t *testing.T) { mux.HandleFunc("/zones/01a7362d577a6c3019a474fd6f485823/spectrum/apps/f68579455bd947efb65ffa1bcf33b52c", handler) - err := client.DeleteSpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") + err := client.DeleteSpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") assert.NoError(t, err) } @@ -351,7 +352,7 @@ func TestSpectrumApplicationProxyProtocolDeprecations(t *testing.T) { setup() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": { @@ -397,7 +398,7 @@ func TestSpectrumApplicationProxyProtocolDeprecations(t *testing.T) { TLS: "off", } - actual, err := client.SpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") + actual, err := client.SpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -411,7 +412,7 @@ func TestSpectrumApplicationEdgeIPs(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -467,7 +468,7 @@ func TestSpectrumApplicationEdgeIPs(t *testing.T) { }, } - actual, err := client.SpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") + actual, err := client.SpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -478,7 +479,7 @@ func TestSpectrumApplicationPortRange(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -541,7 +542,7 @@ func TestSpectrumApplicationPortRange(t *testing.T) { }, } - actual, err := client.SpectrumApplication("01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") + actual, err := client.SpectrumApplication(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "f68579455bd947efb65ffa1bcf33b52c") if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/ssl.go b/ssl.go index 3015b6170cb..6e3cc8b4674 100644 --- a/ssl.go +++ b/ssl.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -62,9 +64,9 @@ type ZoneCustomSSLPriority struct { // CreateSSL allows you to add a custom SSL certificate to the given zone. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-create-ssl-configuration -func (api *API) CreateSSL(zoneID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { +func (api *API) CreateSSL(ctx context.Context, zoneID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("POST", uri, options) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, options) if err != nil { return ZoneCustomSSL{}, err } @@ -78,9 +80,9 @@ func (api *API) CreateSSL(zoneID string, options ZoneCustomSSLOptions) (ZoneCust // ListSSL lists the custom certificates for the given zone. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-list-ssl-configurations -func (api *API) ListSSL(zoneID string) ([]ZoneCustomSSL, error) { +func (api *API) ListSSL(ctx context.Context, zoneID string) ([]ZoneCustomSSL, error) { uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -94,9 +96,9 @@ func (api *API) ListSSL(zoneID string) ([]ZoneCustomSSL, error) { // SSLDetails returns the configuration details for a custom SSL certificate. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-ssl-configuration-details -func (api *API) SSLDetails(zoneID, certificateID string) (ZoneCustomSSL, error) { +func (api *API) SSLDetails(ctx context.Context, zoneID, certificateID string) (ZoneCustomSSL, error) { uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ZoneCustomSSL{}, err } @@ -110,9 +112,9 @@ func (api *API) SSLDetails(zoneID, certificateID string) (ZoneCustomSSL, error) // UpdateSSL updates (replaces) a custom SSL certificate. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-update-ssl-configuration -func (api *API) UpdateSSL(zoneID, certificateID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { +func (api *API) UpdateSSL(ctx context.Context, zoneID, certificateID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("PATCH", uri, options) + res, err := api.makeRequestContext(ctx, "PATCH", uri, options) if err != nil { return ZoneCustomSSL{}, err } @@ -127,14 +129,14 @@ func (api *API) UpdateSSL(zoneID, certificateID string, options ZoneCustomSSLOpt // request) of custom SSL certificates associated with the given zone. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-re-prioritize-ssl-certificates -func (api *API) ReprioritizeSSL(zoneID string, p []ZoneCustomSSLPriority) ([]ZoneCustomSSL, error) { +func (api *API) ReprioritizeSSL(ctx context.Context, zoneID string, p []ZoneCustomSSLPriority) ([]ZoneCustomSSL, error) { uri := "/zones/" + zoneID + "/custom_certificates/prioritize" params := struct { Certificates []ZoneCustomSSLPriority `json:"certificates"` }{ Certificates: p, } - res, err := api.makeRequest("PUT", uri, params) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params) if err != nil { return nil, err } @@ -148,9 +150,9 @@ func (api *API) ReprioritizeSSL(zoneID string, p []ZoneCustomSSLPriority) ([]Zon // DeleteSSL deletes a custom SSL certificate from the given zone. // // API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-delete-an-ssl-certificate -func (api *API) DeleteSSL(zoneID, certificateID string) error { +func (api *API) DeleteSSL(ctx context.Context, zoneID, certificateID string) error { uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { + if _, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil); err != nil { return err } return nil diff --git a/ssl_test.go b/ssl_test.go index 4645a8de670..5fdb8bd4386 100644 --- a/ssl_test.go +++ b/ssl_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "io/ioutil" "net/http" @@ -15,7 +16,7 @@ func TestCreateSSL(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() @@ -71,7 +72,7 @@ func TestCreateSSL(t *testing.T) { Priority: 1, } - actual, err := client.CreateSSL("023e105f4ecef8ad9ca31a8372d0c353", ZoneCustomSSLOptions{ + actual, err := client.CreateSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", ZoneCustomSSLOptions{ Certificate: "-----BEGIN CERTIFICATE----- MIIDtTCCAp2gAwIBAgIJAM15n7fdxhRtMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTQwMzExMTkyMTU5WhcNMTQwNDEwMTkyMTU5WjBF MQswCQYDVQQGEwJVUzETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAvq3sKsHpeduJHimOK+fvQdKsI8z8A05MZyyLp2/R/GE8FjNv+hkVY1WQ LIyTNNQH7CJecE1nbTfo8Y56S7x/rhxC6/DJ8MIulapFPnorq46KU6yRxiM0MQ3N nTJHlHA2ozZta6YBBfVfhHWl1F0IfNbXCLKvGwWWMbCx43OfW6KTkbRnE6gFWKuO fSO5h2u5TaWVuSIzBvYs7Vza6m+gtYAvKAJV2nSZ+eSEFPDo29corOy8+huEOUL8 5FAw4BFPsr1TlrlGPFitduQUHGrSL7skk1ESGza0to3bOtrodKei2s9bk5MXm7lZ qI+WZJX4Zu9+mzZhc9pCVi8r/qlXuQIDAQABo4GnMIGkMB0GA1UdDgQWBBRvavf+ sWM4IwKiH9X9w1vl6nUVRDB1BgNVHSMEbjBsgBRvavf+sWM4IwKiH9X9w1vl6nUV RKFJpEcwRTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAM15n7fdxhRtMAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBABY2ZzBaW0dMsAAT7tPJzrVWVzQx6KU4 UEBLudIlWPlkAwTnINCWR/8eNjCCmGA4heUdHmazdpPa8RzwOmc0NT1NQqzSyktt vTqb4iHD7+8f9MqJ9/FssCfTtqr/Qst/hGH4Wmdf1EJ/6FqYAAb5iRlPgshFZxU8 uXtA8hWn6fK6eISD9HBdcAFToUvKNZ1BIDPvh9f95Ine8ar6yGd56TUNrHR8eHBs ESxz5ddVR/oWRysNJ+aGAyYqHS8S/ttmC7r4XCAHqXptkHPCGRqkAhsterYhd4I8 /cBzejUobNCjjHFbtkAL/SjxZOLW+pNkZwfeYdM8iPkD54Uua1v2tdw= -----END CERTIFICATE-----", PrivateKey: "-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAl 1cSc0vfcJLI4ZdWjiZZqy86Eof4czCwilyjXdvHqbdgDjz9H6K/0FX78EzVdfyExESptPCDl5YYjvcZyAWlgNfYEpFpGeoh/pTFW3hlyKImh4EgBXbDrR251J Ew2Nf56X3duibI6X20gKZA6cvdmWeKh MOOXuh1bSPU3dkb4YOF/fng5iGrx0q3txdMQXTPMZ1uXHFcBH7idgViYesXUBhdll3GP1N Y8laq0yrqh 8HMsZK m27MebqonbNmjOqE218lVEvjCdRO6xvNXrO6vNJBoGn2eGwZ8BVd0mTA3Tj43/2cmxQFY9FLq56cCXqYI1fbRRib ZLrjSNkwIDAQABAoIBABfAjjsjjxc0NxcYvKOMUb9Rpj8Sx6U/o/tDC5u XmsGX37aaJmC5yw9BQiAxgvXtQryEl5uoNoqOdsxzKV6yM0vPcwKEJVBd4G6yx6AjVJZnc2qf72erR7BbA2CQh scMDRBKE041HhgTBRNP6roim0SOgYP5JZIrGAQXNIkyE0fZc5gZNUt388ne/mjWM6Xi08BDGurLC68nsdt7Nd UYqeBVxo2EqChp5vKYZYEcG8h9XBj4u4NIwg1Mty2JqX30uBjoHvF5w/pMs8lG uvj6JR9I 19wtCuccbAJl 4cUq03UQoIDmwejea oC8A8WJr3vVpODDWrvAsjllGPBECgYEAyQRa6edYO6bsSvgbM13qXW9OQTn9YmgzfN24Ux1D66TQU6sBSLdfSHshDhTCi Ax 698aJNRWujAakA2DDgspSx98aRnHbF zvY7i7iWGesN6uN0zL 6/MK5uWoieGZRjgk230fLk00l4/FK1mJIp0apr0Lis9xmDjP5AaUPTUUCgYEAwXuhTHZWPT6v8YwOksjbuK UDkIIvyMux53kb73vrkgMboS4DB1zMLNyG 9EghS414CFROUwGl4ZUKboH1Jo5G34y8VgDuHjirTqL2H6 zNpML iMrWCXjpFKkxwPbeQnEAZ 5Rud4d PTyXAt71blZHE9tZ4KHy8cU1iKc9APcCgYAIqKZd4vg7AZK2G//X85iv06aUSrIudfyZyVcyRVVyphPPNtOEVVnGXn9rAtvqeIrOo52BR68 cj4vlXp hkDuEH QVBuY/NdQhOzFtPrKPQTJdGjIlQ2x65Vidj7r3sRukNkLPyV2v D885zcpTkp83JFuWTYiIrg275DIuAI3QKBgAglM0IrzS g3vlVQxvM1ussgRgkkYeybHq82 wUW 3DXLqeXb0s1DedplUkuoabZriz0Wh4GZFSmtA5ZpZC uV697lkYsndmp2xRhaekllW7bu pY5q88URwO2p8CO5AZ6CWFWuBwSDML5VOapGRqDRgwaD oGpb7fb7IgHOls7AoGBAJnL6Q8t35uYJ8J8hY7wso88IE04z6VaT8WganxcndesWER9eFQDHDDy//ZYeyt6M41uIY CL Vkm9Kwl/bHLJKdnOE1a9NdE6mtfah0Bk2u/YOuzyu5mmcgZiX X/OZuEbGmmbZOR1FCuIyrNYfwYohhcZP7/r0Ia/1GpkHc3Bi-----END RSA PRIVATE KEY-----", BundleMethod: "ubiquitous", @@ -82,7 +83,7 @@ func TestCreateSSL(t *testing.T) { assert.Equal(t, want, actual) } - _, err = client.CreateSSL("bar", ZoneCustomSSLOptions{}) + _, err = client.CreateSSL(context.TODO(), "bar", ZoneCustomSSLOptions{}) assert.Error(t, err) } @@ -91,7 +92,7 @@ func TestListSSL(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -146,12 +147,12 @@ func TestListSSL(t *testing.T) { Priority: 1, } - actual, err := client.ListSSL("023e105f4ecef8ad9ca31a8372d0c353") + actual, err := client.ListSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.ListSSL("bar") + _, err = client.ListSSL(context.TODO(), "bar") assert.Error(t, err) } @@ -204,12 +205,12 @@ func TestSSLDetails(t *testing.T) { Priority: 1, } - actual, err := client.SSLDetails("023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c") + actual, err := client.SSLDetails(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c") if assert.NoError(t, err) { assert.Equal(t, want, actual) } - _, err = client.SSLDetails("023e105f4ecef8ad9ca31a8372d0c353", "bar") + _, err = client.SSLDetails(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "bar") assert.Error(t, err) } @@ -273,7 +274,7 @@ func TestUpdateSSL(t *testing.T) { Priority: 1, } - actual, err := client.UpdateSSL("023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c", ZoneCustomSSLOptions{ + actual, err := client.UpdateSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c", ZoneCustomSSLOptions{ Certificate: "-----BEGIN CERTIFICATE----- MIIDtTCCAp2gAwIBAgIJAM15n7fdxhRtMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV BAYTAlVTMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX aWRnaXRzIFB0eSBMdGQwHhcNMTQwMzExMTkyMTU5WhcNMTQwNDEwMTkyMTU5WjBF MQswCQYDVQQGEwJVUzETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50 ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB CgKCAQEAvq3sKsHpeduJHimOK+fvQdKsI8z8A05MZyyLp2/R/GE8FjNv+hkVY1WQ LIyTNNQH7CJecE1nbTfo8Y56S7x/rhxC6/DJ8MIulapFPnorq46KU6yRxiM0MQ3N nTJHlHA2ozZta6YBBfVfhHWl1F0IfNbXCLKvGwWWMbCx43OfW6KTkbRnE6gFWKuO fSO5h2u5TaWVuSIzBvYs7Vza6m+gtYAvKAJV2nSZ+eSEFPDo29corOy8+huEOUL8 5FAw4BFPsr1TlrlGPFitduQUHGrSL7skk1ESGza0to3bOtrodKei2s9bk5MXm7lZ qI+WZJX4Zu9+mzZhc9pCVi8r/qlXuQIDAQABo4GnMIGkMB0GA1UdDgQWBBRvavf+ sWM4IwKiH9X9w1vl6nUVRDB1BgNVHSMEbjBsgBRvavf+sWM4IwKiH9X9w1vl6nUV RKFJpEcwRTELMAkGA1UEBhMCVVMxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNV BAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZIIJAM15n7fdxhRtMAwGA1UdEwQF MAMBAf8wDQYJKoZIhvcNAQEFBQADggEBABY2ZzBaW0dMsAAT7tPJzrVWVzQx6KU4 UEBLudIlWPlkAwTnINCWR/8eNjCCmGA4heUdHmazdpPa8RzwOmc0NT1NQqzSyktt vTqb4iHD7+8f9MqJ9/FssCfTtqr/Qst/hGH4Wmdf1EJ/6FqYAAb5iRlPgshFZxU8 uXtA8hWn6fK6eISD9HBdcAFToUvKNZ1BIDPvh9f95Ine8ar6yGd56TUNrHR8eHBs ESxz5ddVR/oWRysNJ+aGAyYqHS8S/ttmC7r4XCAHqXptkHPCGRqkAhsterYhd4I8 /cBzejUobNCjjHFbtkAL/SjxZOLW+pNkZwfeYdM8iPkD54Uua1v2tdw= -----END CERTIFICATE-----", PrivateKey: "-----BEGIN RSA PRIVATE KEY-----MIIEowIBAAKCAQEAl 1cSc0vfcJLI4ZdWjiZZqy86Eof4czCwilyjXdvHqbdgDjz9H6K/0FX78EzVdfyExESptPCDl5YYjvcZyAWlgNfYEpFpGeoh/pTFW3hlyKImh4EgBXbDrR251J Ew2Nf56X3duibI6X20gKZA6cvdmWeKh MOOXuh1bSPU3dkb4YOF/fng5iGrx0q3txdMQXTPMZ1uXHFcBH7idgViYesXUBhdll3GP1N Y8laq0yrqh 8HMsZK m27MebqonbNmjOqE218lVEvjCdRO6xvNXrO6vNJBoGn2eGwZ8BVd0mTA3Tj43/2cmxQFY9FLq56cCXqYI1fbRRib ZLrjSNkwIDAQABAoIBABfAjjsjjxc0NxcYvKOMUb9Rpj8Sx6U/o/tDC5u XmsGX37aaJmC5yw9BQiAxgvXtQryEl5uoNoqOdsxzKV6yM0vPcwKEJVBd4G6yx6AjVJZnc2qf72erR7BbA2CQh scMDRBKE041HhgTBRNP6roim0SOgYP5JZIrGAQXNIkyE0fZc5gZNUt388ne/mjWM6Xi08BDGurLC68nsdt7Nd UYqeBVxo2EqChp5vKYZYEcG8h9XBj4u4NIwg1Mty2JqX30uBjoHvF5w/pMs8lG uvj6JR9I 19wtCuccbAJl 4cUq03UQoIDmwejea oC8A8WJr3vVpODDWrvAsjllGPBECgYEAyQRa6edYO6bsSvgbM13qXW9OQTn9YmgzfN24Ux1D66TQU6sBSLdfSHshDhTCi Ax 698aJNRWujAakA2DDgspSx98aRnHbF zvY7i7iWGesN6uN0zL 6/MK5uWoieGZRjgk230fLk00l4/FK1mJIp0apr0Lis9xmDjP5AaUPTUUCgYEAwXuhTHZWPT6v8YwOksjbuK UDkIIvyMux53kb73vrkgMboS4DB1zMLNyG 9EghS414CFROUwGl4ZUKboH1Jo5G34y8VgDuHjirTqL2H6 zNpML iMrWCXjpFKkxwPbeQnEAZ 5Rud4d PTyXAt71blZHE9tZ4KHy8cU1iKc9APcCgYAIqKZd4vg7AZK2G//X85iv06aUSrIudfyZyVcyRVVyphPPNtOEVVnGXn9rAtvqeIrOo52BR68 cj4vlXp hkDuEH QVBuY/NdQhOzFtPrKPQTJdGjIlQ2x65Vidj7r3sRukNkLPyV2v D885zcpTkp83JFuWTYiIrg275DIuAI3QKBgAglM0IrzS g3vlVQxvM1ussgRgkkYeybHq82 wUW 3DXLqeXb0s1DedplUkuoabZriz0Wh4GZFSmtA5ZpZC uV697lkYsndmp2xRhaekllW7bu pY5q88URwO2p8CO5AZ6CWFWuBwSDML5VOapGRqDRgwaD oGpb7fb7IgHOls7AoGBAJnL6Q8t35uYJ8J8hY7wso88IE04z6VaT8WganxcndesWER9eFQDHDDy//ZYeyt6M41uIY CL Vkm9Kwl/bHLJKdnOE1a9NdE6mtfah0Bk2u/YOuzyu5mmcgZiX X/OZuEbGmmbZOR1FCuIyrNYfwYohhcZP7/r0Ia/1GpkHc3Bi-----END RSA PRIVATE KEY-----", BundleMethod: "ubiquitous", @@ -283,7 +284,7 @@ func TestUpdateSSL(t *testing.T) { assert.Equal(t, want, actual) } - _, err = client.UpdateSSL("023e105f4ecef8ad9ca31a8372d0c353", "bar", ZoneCustomSSLOptions{}) + _, err = client.UpdateSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "bar", ZoneCustomSSLOptions{}) assert.Error(t, err) } @@ -292,7 +293,7 @@ func TestReprioritizeSSL(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) b, err := ioutil.ReadAll(r.Body) defer r.Body.Close() if assert.NoError(t, err) { @@ -357,7 +358,7 @@ func TestReprioritizeSSL(t *testing.T) { Priority: 1, } - actual, err := client.ReprioritizeSSL("023e105f4ecef8ad9ca31a8372d0c353", []ZoneCustomSSLPriority{ + actual, err := client.ReprioritizeSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", []ZoneCustomSSLPriority{ {ID: "5a7805061c76ada191ed06f989cc3dac", Priority: 2}, {ID: "9a7806061c88ada191ed06f989cc3dac", Priority: 1}, }) @@ -372,7 +373,7 @@ func TestDeleteSSL(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "id": "7e7b8deba8538af625850b7b2530034c" @@ -381,9 +382,9 @@ func TestDeleteSSL(t *testing.T) { mux.HandleFunc("/zones/023e105f4ecef8ad9ca31a8372d0c353/custom_certificates/7e7b8deba8538af625850b7b2530034c", handler) - err := client.DeleteSSL("023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c") + err := client.DeleteSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "7e7b8deba8538af625850b7b2530034c") assert.NoError(t, err, "Expected to successfully delete certificate ID '7e7b8deba8538af625850b7b2530034c', received error instead") - err = client.DeleteSSL("023e105f4ecef8ad9ca31a8372d0c353", "bar") + err = client.DeleteSSL(context.TODO(), "023e105f4ecef8ad9ca31a8372d0c353", "bar") assert.Error(t, err, "Expected to error when attempting to delete certificate ID 'bar', did not receive error instead") } diff --git a/universal_ssl.go b/universal_ssl.go index 35239731efc..02752d5d2bb 100644 --- a/universal_ssl.go +++ b/universal_ssl.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "github.com/pkg/errors" ) @@ -41,9 +43,9 @@ type universalSSLVerificationResponse struct { // UniversalSSLSettingDetails returns the details for a universal ssl setting // // API reference: https://api.cloudflare.com/#universal-ssl-settings-for-a-zone-universal-ssl-settings-details -func (api *API) UniversalSSLSettingDetails(zoneID string) (UniversalSSLSetting, error) { +func (api *API) UniversalSSLSettingDetails(ctx context.Context, zoneID string) (UniversalSSLSetting, error) { uri := "/zones/" + zoneID + "/ssl/universal/settings" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return UniversalSSLSetting{}, err } @@ -57,9 +59,9 @@ func (api *API) UniversalSSLSettingDetails(zoneID string) (UniversalSSLSetting, // EditUniversalSSLSetting edits the universal ssl setting for a zone // // API reference: https://api.cloudflare.com/#universal-ssl-settings-for-a-zone-edit-universal-ssl-settings -func (api *API) EditUniversalSSLSetting(zoneID string, setting UniversalSSLSetting) (UniversalSSLSetting, error) { +func (api *API) EditUniversalSSLSetting(ctx context.Context, zoneID string, setting UniversalSSLSetting) (UniversalSSLSetting, error) { uri := "/zones/" + zoneID + "/ssl/universal/settings" - res, err := api.makeRequest("PATCH", uri, setting) + res, err := api.makeRequestContext(ctx, "PATCH", uri, setting) if err != nil { return UniversalSSLSetting{}, err } @@ -74,9 +76,9 @@ func (api *API) EditUniversalSSLSetting(zoneID string, setting UniversalSSLSetti // UniversalSSLVerificationDetails returns the details for a universal ssl verification // // API reference: https://api.cloudflare.com/#ssl-verification-ssl-verification-details -func (api *API) UniversalSSLVerificationDetails(zoneID string) ([]UniversalSSLVerificationDetails, error) { +func (api *API) UniversalSSLVerificationDetails(ctx context.Context, zoneID string) ([]UniversalSSLVerificationDetails, error) { uri := "/zones/" + zoneID + "/ssl/verification" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []UniversalSSLVerificationDetails{}, err } diff --git a/universal_ssl_test.go b/universal_ssl_test.go index a6a7b662ea6..afbf1c1ae7c 100644 --- a/universal_ssl_test.go +++ b/universal_ssl_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "io/ioutil" "net/http" @@ -16,7 +17,7 @@ func TestUniversalSSLSettingDetails(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -34,7 +35,7 @@ func TestUniversalSSLSettingDetails(t *testing.T) { Enabled: true, } - got, err := client.UniversalSSLSettingDetails(testZoneID) + got, err := client.UniversalSSLSettingDetails(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, got) } @@ -73,7 +74,7 @@ func TestEditUniversalSSLSetting(t *testing.T) { Enabled: true, } - got, err := client.EditUniversalSSLSetting(testZoneID, want) + got, err := client.EditUniversalSSLSetting(context.TODO(), testZoneID, want) if assert.NoError(t, err) { assert.Equal(t, want, got) } @@ -86,7 +87,7 @@ func TestUniversalSSLVerificationDetails(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "result": [{ @@ -121,7 +122,7 @@ func TestUniversalSSLVerificationDetails(t *testing.T) { }, } - got, err := client.UniversalSSLVerificationDetails(testZoneID) + got, err := client.UniversalSSLVerificationDetails(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, got) } diff --git a/user.go b/user.go index b8a7148928d..a1e06826e91 100644 --- a/user.go +++ b/user.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "time" "github.com/pkg/errors" @@ -61,9 +63,9 @@ type UserBillingProfile struct { // UserDetails provides information about the logged-in user. // // API reference: https://api.cloudflare.com/#user-user-details -func (api *API) UserDetails() (User, error) { +func (api *API) UserDetails(ctx context.Context) (User, error) { var r UserResponse - res, err := api.makeRequest("GET", "/user", nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user", nil) if err != nil { return User{}, err } @@ -79,9 +81,9 @@ func (api *API) UserDetails() (User, error) { // UpdateUser updates the properties of the given user. // // API reference: https://api.cloudflare.com/#user-update-user -func (api *API) UpdateUser(user *User) (User, error) { +func (api *API) UpdateUser(ctx context.Context, user *User) (User, error) { var r UserResponse - res, err := api.makeRequest("PATCH", "/user", user) + res, err := api.makeRequestContext(ctx, "PATCH", "/user", user) if err != nil { return User{}, err } @@ -97,9 +99,9 @@ func (api *API) UpdateUser(user *User) (User, error) { // UserBillingProfile returns the billing profile of the user. // // API reference: https://api.cloudflare.com/#user-billing-profile -func (api *API) UserBillingProfile() (UserBillingProfile, error) { +func (api *API) UserBillingProfile(ctx context.Context) (UserBillingProfile, error) { var r userBillingProfileResponse - res, err := api.makeRequest("GET", "/user/billing/profile", nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/billing/profile", nil) if err != nil { return UserBillingProfile{}, err } diff --git a/user_agent.go b/user_agent.go index 75c3ea0a1b8..89430b648b9 100644 --- a/user_agent.go +++ b/user_agent.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" @@ -40,7 +42,7 @@ type UserAgentRuleListResponse struct { // CreateUserAgentRule creates a User-Agent Block rule for the given zone ID. // // API reference: https://api.cloudflare.com/#user-agent-blocking-rules-create-a-useragent-rule -func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) { +func (api *API) CreateUserAgentRule(ctx context.Context, zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) { switch ld.Mode { case "block", "challenge", "js_challenge", "whitelist": break @@ -49,7 +51,7 @@ func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgent } uri := "/zones/" + zoneID + "/firewall/ua_rules" - res, err := api.makeRequest("POST", uri, ld) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, ld) if err != nil { return nil, err } @@ -66,9 +68,9 @@ func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgent // UpdateUserAgentRule updates a User-Agent Block rule (based on the ID) for the given zone ID. // // API reference: https://api.cloudflare.com/#user-agent-blocking-rules-update-useragent-rule -func (api *API) UpdateUserAgentRule(zoneID string, id string, ld UserAgentRule) (*UserAgentRuleResponse, error) { +func (api *API) UpdateUserAgentRule(ctx context.Context, zoneID string, id string, ld UserAgentRule) (*UserAgentRuleResponse, error) { uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("PUT", uri, ld) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, ld) if err != nil { return nil, err } @@ -85,9 +87,9 @@ func (api *API) UpdateUserAgentRule(zoneID string, id string, ld UserAgentRule) // DeleteUserAgentRule deletes a User-Agent Block rule (based on the ID) for the given zone ID. // // API reference: https://api.cloudflare.com/#user-agent-blocking-rules-delete-useragent-rule -func (api *API) DeleteUserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { +func (api *API) DeleteUserAgentRule(ctx context.Context, zoneID string, id string) (*UserAgentRuleResponse, error) { uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return nil, err } @@ -104,9 +106,9 @@ func (api *API) DeleteUserAgentRule(zoneID string, id string) (*UserAgentRuleRes // UserAgentRule retrieves a User-Agent Block rule (based on the ID) for the given zone ID. // // API reference: https://api.cloudflare.com/#user-agent-blocking-rules-useragent-rule-details -func (api *API) UserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { +func (api *API) UserAgentRule(ctx context.Context, zoneID string, id string) (*UserAgentRuleResponse, error) { uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -123,7 +125,7 @@ func (api *API) UserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, // ListUserAgentRules retrieves a list of User-Agent Block rules for a given zone ID by page number. // // API reference: https://api.cloudflare.com/#user-agent-blocking-rules-list-useragent-rules -func (api *API) ListUserAgentRules(zoneID string, page int) (*UserAgentRuleListResponse, error) { +func (api *API) ListUserAgentRules(ctx context.Context, zoneID string, page int) (*UserAgentRuleListResponse, error) { v := url.Values{} if page <= 0 { page = 1 @@ -134,7 +136,7 @@ func (api *API) ListUserAgentRules(zoneID string, page int) (*UserAgentRuleListR query := "?" + v.Encode() uri := "/zones/" + zoneID + "/firewall/ua_rules" + query - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } diff --git a/user_agent_example_test.go b/user_agent_example_test.go index b4831cc9430..e6053bb428a 100644 --- a/user_agent_example_test.go +++ b/user_agent_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -19,7 +20,7 @@ func ExampleAPI_ListUserAgentRules_all() { } // Fetch all Zone Lockdown rules for a zone, by page. - rules, err := api.ListUserAgentRules(zoneID, 1) + rules, err := api.ListUserAgentRules(context.TODO(), zoneID, 1) if err != nil { log.Fatal(err) } diff --git a/user_test.go b/user_test.go index 061fe9e2cab..904bd791754 100644 --- a/user_test.go +++ b/user_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -15,7 +16,7 @@ func TestUser_UserDetails(t *testing.T) { defer teardown() mux.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -39,7 +40,7 @@ func TestUser_UserDetails(t *testing.T) { }`) }) - user, err := client.UserDetails() + user, err := client.UserDetails(context.TODO()) createdOn, _ := time.Parse(time.RFC3339, "2009-07-01T00:00:00Z") modifiedOn, _ := time.Parse(time.RFC3339, "2016-05-06T20:32:00Z") @@ -111,7 +112,7 @@ func TestUser_UpdateUser(t *testing.T) { TwoFA: false, } - userOut, err := client.UpdateUser(&userIn) + userOut, err := client.UpdateUser(context.TODO(), &userIn) want := User{ ID: "7c5dae5552338874e5053f2534d2767a", @@ -137,7 +138,7 @@ func TestUser_UserBillingProfile(t *testing.T) { defer teardown() mux.HandleFunc("/user/billing/profile", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -168,7 +169,7 @@ func TestUser_UserBillingProfile(t *testing.T) { createdOn, _ := time.Parse(time.RFC3339, "2014-03-01T12:21:02.0000Z") editedOn, _ := time.Parse(time.RFC3339, "2014-04-01T12:21:02.0000Z") - userBillingProfile, err := client.UserBillingProfile() + userBillingProfile, err := client.UserBillingProfile(context.TODO()) want := UserBillingProfile{ ID: "0020c268dbf54e975e7fe8563df49d52", diff --git a/virtualdns.go b/virtualdns.go index 6e6162265a4..0b76bc9c6fd 100644 --- a/virtualdns.go +++ b/virtualdns.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strings" "time" @@ -68,8 +70,8 @@ type VirtualDNSAnalyticsResponse struct { // CreateVirtualDNS creates a new Virtual DNS cluster. // // API reference: https://api.cloudflare.com/#virtual-dns-users--create-a-virtual-dns-cluster -func (api *API) CreateVirtualDNS(v *VirtualDNS) (*VirtualDNS, error) { - res, err := api.makeRequest("POST", "/user/virtual_dns", v) +func (api *API) CreateVirtualDNS(ctx context.Context, v *VirtualDNS) (*VirtualDNS, error) { + res, err := api.makeRequestContext(ctx, http.MethodPost, "/user/virtual_dns", v) if err != nil { return nil, err } @@ -86,9 +88,9 @@ func (api *API) CreateVirtualDNS(v *VirtualDNS) (*VirtualDNS, error) { // VirtualDNS fetches a single virtual DNS cluster. // // API reference: https://api.cloudflare.com/#virtual-dns-users--get-a-virtual-dns-cluster -func (api *API) VirtualDNS(virtualDNSID string) (*VirtualDNS, error) { +func (api *API) VirtualDNS(ctx context.Context, virtualDNSID string) (*VirtualDNS, error) { uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -105,8 +107,8 @@ func (api *API) VirtualDNS(virtualDNSID string) (*VirtualDNS, error) { // ListVirtualDNS lists the virtual DNS clusters associated with an account. // // API reference: https://api.cloudflare.com/#virtual-dns-users--get-virtual-dns-clusters -func (api *API) ListVirtualDNS() ([]*VirtualDNS, error) { - res, err := api.makeRequest("GET", "/user/virtual_dns", nil) +func (api *API) ListVirtualDNS(ctx context.Context) ([]*VirtualDNS, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/user/virtual_dns", nil) if err != nil { return nil, err } @@ -123,9 +125,9 @@ func (api *API) ListVirtualDNS() ([]*VirtualDNS, error) { // UpdateVirtualDNS updates a Virtual DNS cluster. // // API reference: https://api.cloudflare.com/#virtual-dns-users--modify-a-virtual-dns-cluster -func (api *API) UpdateVirtualDNS(virtualDNSID string, vv VirtualDNS) error { +func (api *API) UpdateVirtualDNS(ctx context.Context, virtualDNSID string, vv VirtualDNS) error { uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("PUT", uri, vv) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, vv) if err != nil { return err } @@ -143,9 +145,9 @@ func (api *API) UpdateVirtualDNS(virtualDNSID string, vv VirtualDNS) error { // undone, and will stop all traffic to that cluster. // // API reference: https://api.cloudflare.com/#virtual-dns-users--delete-a-virtual-dns-cluster -func (api *API) DeleteVirtualDNS(virtualDNSID string) error { +func (api *API) DeleteVirtualDNS(ctx context.Context, virtualDNSID string) error { uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } @@ -175,9 +177,9 @@ func (o VirtualDNSUserAnalyticsOptions) encode() string { } // VirtualDNSUserAnalytics retrieves analytics report for a specified dimension and time range -func (api *API) VirtualDNSUserAnalytics(virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) { +func (api *API) VirtualDNSUserAnalytics(ctx context.Context, virtualDNSID string, o VirtualDNSUserAnalyticsOptions) (VirtualDNSAnalytics, error) { uri := "/user/virtual_dns/" + virtualDNSID + "/dns_analytics/report?" + o.encode() - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return VirtualDNSAnalytics{}, err } diff --git a/virtualdns_test.go b/virtualdns_test.go index 422f5c1e0b4..69f74a3ba4a 100644 --- a/virtualdns_test.go +++ b/virtualdns_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "testing" @@ -28,7 +29,7 @@ func TestVirtualDNSUserAnalytics(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { expectedMetrics := "queryCount,uncachedCount,staleCount,responseTimeAvg,responseTimeMedia,responseTime90th,responseTime99th" - assert.Equal(t, r.Method, "GET", "Expected method 'GET'") + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET'") assert.Equal(t, expectedMetrics, r.URL.Query().Get("metrics"), "Expected many metrics in URL parameter") assert.Equal(t, since.Format(time.RFC3339), r.URL.Query().Get("since"), "Expected since parameter in URL") assert.Equal(t, until.Format(time.RFC3339), r.URL.Query().Get("until"), "Expected until parameter in URL") @@ -78,7 +79,7 @@ func TestVirtualDNSUserAnalytics(t *testing.T) { Since: &since, Until: &until, } - actual, err := client.VirtualDNSUserAnalytics("12345", params) + actual, err := client.VirtualDNSUserAnalytics(context.TODO(), "12345", params) if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/waf.go b/waf.go index c52dd124e40..3f1a190e3df 100644 --- a/waf.go +++ b/waf.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "net/url" "strconv" @@ -102,7 +104,7 @@ type WAFRuleOptions struct { // ListWAFPackages returns a slice of the WAF packages for the given zone. // // API Reference: https://api.cloudflare.com/#waf-rule-packages-list-firewall-packages -func (api *API) ListWAFPackages(zoneID string) ([]WAFPackage, error) { +func (api *API) ListWAFPackages(ctx context.Context, zoneID string) ([]WAFPackage, error) { // Construct a query string v := url.Values{} // Request as many WAF packages as possible per page - API max is 100 @@ -118,7 +120,7 @@ func (api *API) ListWAFPackages(zoneID string) ([]WAFPackage, error) { v.Set("page", strconv.Itoa(page)) query := "?" + v.Encode() uri := "/zones/" + zoneID + "/firewall/waf/packages" + query - res, err = api.makeRequest("GET", uri, nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []WAFPackage{}, err } @@ -149,9 +151,9 @@ func (api *API) ListWAFPackages(zoneID string) ([]WAFPackage, error) { // WAFPackage returns a WAF package for the given zone. // // API Reference: https://api.cloudflare.com/#waf-rule-packages-firewall-package-details -func (api *API) WAFPackage(zoneID, packageID string) (WAFPackage, error) { +func (api *API) WAFPackage(ctx context.Context, zoneID, packageID string) (WAFPackage, error) { uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WAFPackage{}, err } @@ -168,9 +170,9 @@ func (api *API) WAFPackage(zoneID, packageID string) (WAFPackage, error) { // UpdateWAFPackage lets you update the a WAF Package. // // API Reference: https://api.cloudflare.com/#waf-rule-packages-edit-firewall-package -func (api *API) UpdateWAFPackage(zoneID, packageID string, opts WAFPackageOptions) (WAFPackage, error) { +func (api *API) UpdateWAFPackage(ctx context.Context, zoneID, packageID string, opts WAFPackageOptions) (WAFPackage, error) { uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID - res, err := api.makeRequest("PATCH", uri, opts) + res, err := api.makeRequestContext(ctx, "PATCH", uri, opts) if err != nil { return WAFPackage{}, err } @@ -186,7 +188,7 @@ func (api *API) UpdateWAFPackage(zoneID, packageID string, opts WAFPackageOption // ListWAFGroups returns a slice of the WAF groups for the given WAF package. // // API Reference: https://api.cloudflare.com/#waf-rule-groups-list-rule-groups -func (api *API) ListWAFGroups(zoneID, packageID string) ([]WAFGroup, error) { +func (api *API) ListWAFGroups(ctx context.Context, zoneID, packageID string) ([]WAFGroup, error) { // Construct a query string v := url.Values{} // Request as many WAF groups as possible per page - API max is 100 @@ -202,7 +204,7 @@ func (api *API) ListWAFGroups(zoneID, packageID string) ([]WAFGroup, error) { v.Set("page", strconv.Itoa(page)) query := "?" + v.Encode() uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/groups" + query - res, err = api.makeRequest("GET", uri, nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []WAFGroup{}, err } @@ -232,9 +234,9 @@ func (api *API) ListWAFGroups(zoneID, packageID string) ([]WAFGroup, error) { // WAFGroup returns a WAF rule group from the given WAF package. // // API Reference: https://api.cloudflare.com/#waf-rule-groups-rule-group-details -func (api *API) WAFGroup(zoneID, packageID, groupID string) (WAFGroup, error) { +func (api *API) WAFGroup(ctx context.Context, zoneID, packageID, groupID string) (WAFGroup, error) { uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/groups/" + groupID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WAFGroup{}, err } @@ -251,10 +253,10 @@ func (api *API) WAFGroup(zoneID, packageID, groupID string) (WAFGroup, error) { // UpdateWAFGroup lets you update the mode of a WAF Group. // // API Reference: https://api.cloudflare.com/#waf-rule-groups-edit-rule-group -func (api *API) UpdateWAFGroup(zoneID, packageID, groupID, mode string) (WAFGroup, error) { +func (api *API) UpdateWAFGroup(ctx context.Context, zoneID, packageID, groupID, mode string) (WAFGroup, error) { opts := WAFRuleOptions{Mode: mode} uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/groups/" + groupID - res, err := api.makeRequest("PATCH", uri, opts) + res, err := api.makeRequestContext(ctx, "PATCH", uri, opts) if err != nil { return WAFGroup{}, err } @@ -270,7 +272,7 @@ func (api *API) UpdateWAFGroup(zoneID, packageID, groupID, mode string) (WAFGrou // ListWAFRules returns a slice of the WAF rules for the given WAF package. // // API Reference: https://api.cloudflare.com/#waf-rules-list-rules -func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) { +func (api *API) ListWAFRules(ctx context.Context, zoneID, packageID string) ([]WAFRule, error) { // Construct a query string v := url.Values{} // Request as many WAF rules as possible per page - API max is 100 @@ -286,7 +288,7 @@ func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) { v.Set("page", strconv.Itoa(page)) query := "?" + v.Encode() uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules" + query - res, err = api.makeRequest("GET", uri, nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []WAFRule{}, err } @@ -317,9 +319,9 @@ func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) { // WAFRule returns a WAF rule from the given WAF package. // // API Reference: https://api.cloudflare.com/#waf-rules-rule-details -func (api *API) WAFRule(zoneID, packageID, ruleID string) (WAFRule, error) { +func (api *API) WAFRule(ctx context.Context, zoneID, packageID, ruleID string) (WAFRule, error) { uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules/" + ruleID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WAFRule{}, err } @@ -336,10 +338,10 @@ func (api *API) WAFRule(zoneID, packageID, ruleID string) (WAFRule, error) { // UpdateWAFRule lets you update the mode of a WAF Rule. // // API Reference: https://api.cloudflare.com/#waf-rules-edit-rule -func (api *API) UpdateWAFRule(zoneID, packageID, ruleID, mode string) (WAFRule, error) { +func (api *API) UpdateWAFRule(ctx context.Context, zoneID, packageID, ruleID, mode string) (WAFRule, error) { opts := WAFRuleOptions{Mode: mode} uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules/" + ruleID - res, err := api.makeRequest("PATCH", uri, opts) + res, err := api.makeRequestContext(ctx, "PATCH", uri, opts) if err != nil { return WAFRule{}, err } diff --git a/waf_overrides.go b/waf_overrides.go index 5630eb9ba46..db850a21f6c 100644 --- a/waf_overrides.go +++ b/waf_overrides.go @@ -1,7 +1,9 @@ package cloudflare import ( + "context" "encoding/json" + "net/http" "github.com/pkg/errors" ) @@ -35,13 +37,13 @@ type WAFOverride struct { // ListWAFOverrides returns a slice of the WAF overrides. // // API Reference: https://api.cloudflare.com/#waf-overrides-list-uri-controlled-waf-configurations -func (api *API) ListWAFOverrides(zoneID string) ([]WAFOverride, error) { +func (api *API) ListWAFOverrides(ctx context.Context, zoneID string) ([]WAFOverride, error) { var overrides []WAFOverride var res []byte var err error uri := "/zones/" + zoneID + "/firewall/waf/overrides" - res, err = api.makeRequest("GET", uri, nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []WAFOverride{}, err } @@ -66,9 +68,9 @@ func (api *API) ListWAFOverrides(zoneID string) ([]WAFOverride, error) { // WAFOverride returns a WAF override from the given override ID. // // API Reference: https://api.cloudflare.com/#waf-overrides-uri-controlled-waf-configuration-details -func (api *API) WAFOverride(zoneID, overrideID string) (WAFOverride, error) { +func (api *API) WAFOverride(ctx context.Context, zoneID, overrideID string) (WAFOverride, error) { uri := "/zones/" + zoneID + "/firewall/waf/overrides/" + overrideID - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WAFOverride{}, err } @@ -85,9 +87,9 @@ func (api *API) WAFOverride(zoneID, overrideID string) (WAFOverride, error) { // CreateWAFOverride creates a new WAF override. // // API reference: https://api.cloudflare.com/#waf-overrides-create-a-uri-controlled-waf-configuration -func (api *API) CreateWAFOverride(zoneID string, override WAFOverride) (WAFOverride, error) { +func (api *API) CreateWAFOverride(ctx context.Context, zoneID string, override WAFOverride) (WAFOverride, error) { uri := "/zones/" + zoneID + "/firewall/waf/overrides" - res, err := api.makeRequest("POST", uri, override) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, override) if err != nil { return WAFOverride{}, err } @@ -101,10 +103,10 @@ func (api *API) CreateWAFOverride(zoneID string, override WAFOverride) (WAFOverr // UpdateWAFOverride updates an existing WAF override. // // API reference: https://api.cloudflare.com/#waf-overrides-update-uri-controlled-waf-configuration -func (api *API) UpdateWAFOverride(zoneID, overrideID string, override WAFOverride) (WAFOverride, error) { +func (api *API) UpdateWAFOverride(ctx context.Context, zoneID, overrideID string, override WAFOverride) (WAFOverride, error) { uri := "/zones/" + zoneID + "/firewall/waf/overrides/" + overrideID - res, err := api.makeRequest("PUT", uri, override) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, override) if err != nil { return WAFOverride{}, err } @@ -121,9 +123,9 @@ func (api *API) UpdateWAFOverride(zoneID, overrideID string, override WAFOverrid // DeleteWAFOverride deletes a WAF override for a zone. // // API reference: https://api.cloudflare.com/#waf-overrides-delete-lockdown-rule -func (api *API) DeleteWAFOverride(zoneID, overrideID string) error { +func (api *API) DeleteWAFOverride(ctx context.Context, zoneID, overrideID string) error { uri := "/zones/" + zoneID + "/firewall/waf/overrides/" + overrideID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return err } diff --git a/waf_overrides_test.go b/waf_overrides_test.go index b103ff45013..d87823d2507 100644 --- a/waf_overrides_test.go +++ b/waf_overrides_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + context "context" "fmt" "net/http" "testing" @@ -13,7 +14,7 @@ func TestWAFOverride(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -50,7 +51,7 @@ func TestWAFOverride(t *testing.T) { RewriteAction: map[string]string{"default": "simulate"}, } - actual, err := client.WAFOverride("01a7362d577a6c3019a474fd6f485823", "a27cece9ec0e4af39ae9c58e3326e2b6") + actual, err := client.WAFOverride(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "a27cece9ec0e4af39ae9c58e3326e2b6") if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -63,7 +64,7 @@ func TestListWAFOverrides(t *testing.T) { testZoneID := "xyz123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-overrides-list-uri-controlled-waf-configurations @@ -114,7 +115,7 @@ func TestListWAFOverrides(t *testing.T) { }, } - d, err := client.ListWAFOverrides(testZoneID) + d, err := client.ListWAFOverrides(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, d) @@ -126,7 +127,7 @@ func TestCreateWAFOverride(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -162,7 +163,7 @@ func TestCreateWAFOverride(t *testing.T) { RewriteAction: map[string]string{"default": "simulate"}, } - actual, err := client.CreateWAFOverride("01a7362d577a6c3019a474fd6f485823", want) + actual, err := client.CreateWAFOverride(context.TODO(), "01a7362d577a6c3019a474fd6f485823", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) } @@ -173,7 +174,7 @@ func TestDeleteWAFOverride(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "DELETE", "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodDelete, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -187,7 +188,7 @@ func TestDeleteWAFOverride(t *testing.T) { mux.HandleFunc("/zones/01a7362d577a6c3019a474fd6f485823/firewall/waf/overrides/18a9b91a93364593a8f41bd53bb2c02d", handler) - err := client.DeleteWAFOverride("01a7362d577a6c3019a474fd6f485823", "18a9b91a93364593a8f41bd53bb2c02d") + err := client.DeleteWAFOverride(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "18a9b91a93364593a8f41bd53bb2c02d") assert.NoError(t, err) } @@ -196,7 +197,7 @@ func TestUpdateWAFOverride(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "result": { @@ -232,7 +233,7 @@ func TestUpdateWAFOverride(t *testing.T) { RewriteAction: map[string]string{"default": "block"}, } - actual, err := client.UpdateWAFOverride("01a7362d577a6c3019a474fd6f485823", "e160a4fca2b346a7a418f49da049c566", want) + actual, err := client.UpdateWAFOverride(context.TODO(), "01a7362d577a6c3019a474fd6f485823", "e160a4fca2b346a7a418f49da049c566", want) if assert.NoError(t, err) { assert.Equal(t, want, actual) } diff --git a/waf_test.go b/waf_test.go index a25c9ae9b1c..a1070ab8579 100644 --- a/waf_test.go +++ b/waf_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "io/ioutil" "net/http" @@ -18,7 +19,7 @@ func TestListWAFPackages(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-rule-packages-properties @@ -59,13 +60,13 @@ func TestListWAFPackages(t *testing.T) { }, } - d, err := client.ListWAFPackages(testZoneID) + d, err := client.ListWAFPackages(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -77,7 +78,7 @@ func TestListWAFPackagesMultiplePages(t *testing.T) { page := 1 handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) reqURI, err := url.ParseRequestURI(r.RequestURI) assert.NoError(t, err) @@ -137,13 +138,13 @@ func TestListWAFPackagesMultiplePages(t *testing.T) { }, } - d, err := client.ListWAFPackages(testZoneID) + d, err := client.ListWAFPackages(context.TODO(), testZoneID) if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -154,7 +155,7 @@ func TestWAFPackage(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-rule-packages-properties @@ -186,13 +187,13 @@ func TestWAFPackage(t *testing.T) { ActionMode: "", } - d, err := client.WAFPackage(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") + d, err := client.WAFPackage(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.WAFPackage(testZoneID, "123") + _, err = client.WAFPackage(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -243,7 +244,7 @@ func TestUpdateWAFPackage(t *testing.T) { ActionMode: "challenge", } - d, err := client.UpdateWAFPackage(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", WAFPackageOptions{Sensitivity: "high", ActionMode: "challenge"}) + d, err := client.UpdateWAFPackage(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", WAFPackageOptions{Sensitivity: "high", ActionMode: "challenge"}) if assert.NoError(t, err) { assert.Equal(t, want, d) @@ -257,7 +258,7 @@ func TestListWAFGroups(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") @@ -305,13 +306,13 @@ func TestListWAFGroups(t *testing.T) { }, } - d, err := client.ListWAFGroups(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") + d, err := client.ListWAFGroups(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFGroups(testZoneID, "123") + _, err = client.ListWAFGroups(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -324,7 +325,7 @@ func TestListWAFGroupsMultiplePages(t *testing.T) { page := 1 handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) reqURI, err := url.ParseRequestURI(r.RequestURI) assert.NoError(t, err) @@ -391,13 +392,13 @@ func TestListWAFGroupsMultiplePages(t *testing.T) { }, } - d, err := client.ListWAFGroups(testZoneID, packageID) + d, err := client.ListWAFGroups(context.TODO(), testZoneID, packageID) if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFGroups(testZoneID, "123") + _, err = client.ListWAFGroups(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -408,7 +409,7 @@ func TestWAFGroup(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-rule-groups-rule-group-details @@ -445,13 +446,13 @@ func TestWAFGroup(t *testing.T) { AllowedModes: []string{"on", "off"}, } - d, err := client.WAFGroup(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "de677e5818985db1285d0e80225f06e5") + d, err := client.WAFGroup(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "de677e5818985db1285d0e80225f06e5") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.WAFGroup(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "123") + _, err = client.WAFGroup(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "123") assert.Error(t, err) } @@ -506,7 +507,7 @@ func TestUpdateWAFGroup(t *testing.T) { AllowedModes: []string{"on", "off"}, } - d, err := client.UpdateWAFGroup(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "de677e5818985db1285d0e80225f06e5", "on") + d, err := client.UpdateWAFGroup(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "de677e5818985db1285d0e80225f06e5", "on") if assert.NoError(t, err) { assert.Equal(t, want, d) @@ -520,7 +521,7 @@ func TestListWAFRules(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-rules-properties @@ -575,13 +576,13 @@ func TestListWAFRules(t *testing.T) { }, } - d, err := client.ListWAFRules(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") + d, err := client.ListWAFRules(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -594,7 +595,7 @@ func TestListWAFRulesMultiplePages(t *testing.T) { page := 1 handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) reqURI, err := url.ParseRequestURI(r.RequestURI) assert.NoError(t, err) @@ -675,13 +676,13 @@ func TestListWAFRulesMultiplePages(t *testing.T) { }, } - d, err := client.ListWAFRules(testZoneID, packageID) + d, err := client.ListWAFRules(context.TODO(), testZoneID, packageID) if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -692,7 +693,7 @@ func TestWAFRule(t *testing.T) { testZoneID := "abcd123" handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#waf-rules-properties @@ -737,13 +738,13 @@ func TestWAFRule(t *testing.T) { AllowedModes: []string{"on", "off"}, } - d, err := client.WAFRule(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "f939de3be84e66e757adcdcb87908023") + d, err := client.WAFRule(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "f939de3be84e66e757adcdcb87908023") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } @@ -806,12 +807,12 @@ func TestUpdateWAFRule(t *testing.T) { AllowedModes: []string{"on", "off"}, } - d, err := client.UpdateWAFRule(testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "f939de3be84e66e757adcdcb87908023", "on") + d, err := client.UpdateWAFRule(context.TODO(), testZoneID, "a25a9a7e9c00afc1fb2e0245519d725b", "f939de3be84e66e757adcdcb87908023", "on") if assert.NoError(t, err) { assert.Equal(t, want, d) } - _, err = client.ListWAFRules(testZoneID, "123") + _, err = client.ListWAFRules(context.TODO(), testZoneID, "123") assert.Error(t, err) } diff --git a/workers.go b/workers.go index b5c2eaf370e..11c99723ee3 100644 --- a/workers.go +++ b/workers.go @@ -2,6 +2,7 @@ package cloudflare import ( "bytes" + "context" "encoding/hex" "encoding/json" "fmt" @@ -277,13 +278,13 @@ func getRandomPartName() string { // DeleteWorker deletes worker for a zone. // // API reference: https://api.cloudflare.com/#worker-script-delete-worker -func (api *API) DeleteWorker(requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { +func (api *API) DeleteWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { // if ScriptName is provided we will treat as org request if requestParams.ScriptName != "" { - return api.deleteWorkerWithName(requestParams.ScriptName) + return api.deleteWorkerWithName(ctx, requestParams.ScriptName) } uri := "/zones/" + requestParams.ZoneID + "/workers/script" - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) var r WorkerScriptResponse if err != nil { return r, err @@ -299,12 +300,12 @@ func (api *API) DeleteWorker(requestParams *WorkerRequestParams) (WorkerScriptRe // Sccount must be specified as api option https://godoc.org/github.com/cloudflare/cloudflare-go#UsingAccount // // API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) deleteWorkerWithName(scriptName string) (WorkerScriptResponse, error) { +func (api *API) deleteWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) { if api.AccountID == "" { return WorkerScriptResponse{}, errors.New("account ID required") } uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) var r WorkerScriptResponse if err != nil { return r, err @@ -319,12 +320,12 @@ func (api *API) deleteWorkerWithName(scriptName string) (WorkerScriptResponse, e // DownloadWorker fetch raw script content for your worker returns []byte containing worker code js // // API reference: https://api.cloudflare.com/#worker-script-download-worker -func (api *API) DownloadWorker(requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { +func (api *API) DownloadWorker(ctx context.Context, requestParams *WorkerRequestParams) (WorkerScriptResponse, error) { if requestParams.ScriptName != "" { - return api.downloadWorkerWithName(requestParams.ScriptName) + return api.downloadWorkerWithName(ctx, requestParams.ScriptName) } uri := "/zones/" + requestParams.ZoneID + "/workers/script" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) var r WorkerScriptResponse if err != nil { return r, err @@ -337,12 +338,12 @@ func (api *API) DownloadWorker(requestParams *WorkerRequestParams) (WorkerScript // DownloadWorkerWithName fetch raw script content for your worker returns string containing worker code js // // API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) downloadWorkerWithName(scriptName string) (WorkerScriptResponse, error) { +func (api *API) downloadWorkerWithName(ctx context.Context, scriptName string) (WorkerScriptResponse, error) { if api.AccountID == "" { return WorkerScriptResponse{}, errors.New("account ID required") } uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) var r WorkerScriptResponse if err != nil { return r, err @@ -353,7 +354,7 @@ func (api *API) downloadWorkerWithName(scriptName string) (WorkerScriptResponse, } // ListWorkerBindings returns all the bindings for a particular worker -func (api *API) ListWorkerBindings(requestParams *WorkerRequestParams) (WorkerBindingListResponse, error) { +func (api *API) ListWorkerBindings(ctx context.Context, requestParams *WorkerRequestParams) (WorkerBindingListResponse, error) { if requestParams.ScriptName == "" { return WorkerBindingListResponse{}, errors.New("ScriptName is required") } @@ -368,7 +369,7 @@ func (api *API) ListWorkerBindings(requestParams *WorkerRequestParams) (WorkerBi Bindings []workerBindingMeta `json:"result"` } var r WorkerBindingListResponse - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return r, err } @@ -440,7 +441,7 @@ func (b *bindingContentReader) Read(p []byte) (n int, err error) { // Lazily load the content when Read() is first called if b.content == nil { uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings/%s/content", b.api.AccountID, b.requestParams.ScriptName, b.bindingName) - res, err := b.api.makeRequest("GET", uri, nil) + res, err := b.api.makeRequest(http.MethodGet, uri, nil) if err != nil { return 0, err } @@ -470,12 +471,12 @@ func (b *bindingContentReader) Read(p []byte) (n int, err error) { // ListWorkerScripts returns list of worker scripts for given account. // // API reference: https://developers.cloudflare.com/workers/tooling/api/scripts/ -func (api *API) ListWorkerScripts() (WorkerListResponse, error) { +func (api *API) ListWorkerScripts(ctx context.Context) (WorkerListResponse, error) { if api.AccountID == "" { return WorkerListResponse{}, errors.New("account ID required") } uri := "/accounts/" + api.AccountID + "/workers/scripts" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WorkerListResponse{}, err } @@ -490,32 +491,32 @@ func (api *API) ListWorkerScripts() (WorkerListResponse, error) { // UploadWorker push raw script content for your worker. // // API reference: https://api.cloudflare.com/#worker-script-upload-worker -func (api *API) UploadWorker(requestParams *WorkerRequestParams, data string) (WorkerScriptResponse, error) { +func (api *API) UploadWorker(ctx context.Context, requestParams *WorkerRequestParams, data string) (WorkerScriptResponse, error) { if requestParams.ScriptName != "" { - return api.uploadWorkerWithName(requestParams.ScriptName, "application/javascript", []byte(data)) + return api.uploadWorkerWithName(ctx, requestParams.ScriptName, "application/javascript", []byte(data)) } - return api.uploadWorkerForZone(requestParams.ZoneID, "application/javascript", []byte(data)) + return api.uploadWorkerForZone(ctx, requestParams.ZoneID, "application/javascript", []byte(data)) } // UploadWorkerWithBindings push raw script content and bindings for your worker // // API reference: https://api.cloudflare.com/#worker-script-upload-worker -func (api *API) UploadWorkerWithBindings(requestParams *WorkerRequestParams, data *WorkerScriptParams) (WorkerScriptResponse, error) { +func (api *API) UploadWorkerWithBindings(ctx context.Context, requestParams *WorkerRequestParams, data *WorkerScriptParams) (WorkerScriptResponse, error) { contentType, body, err := formatMultipartBody(data) if err != nil { return WorkerScriptResponse{}, err } if requestParams.ScriptName != "" { - return api.uploadWorkerWithName(requestParams.ScriptName, contentType, body) + return api.uploadWorkerWithName(ctx, requestParams.ScriptName, contentType, body) } - return api.uploadWorkerForZone(requestParams.ZoneID, contentType, body) + return api.uploadWorkerForZone(ctx, requestParams.ZoneID, contentType, body) } -func (api *API) uploadWorkerForZone(zoneID, contentType string, body []byte) (WorkerScriptResponse, error) { +func (api *API) uploadWorkerForZone(ctx context.Context, zoneID, contentType string, body []byte) (WorkerScriptResponse, error) { uri := "/zones/" + zoneID + "/workers/script" headers := make(http.Header) headers.Set("Content-Type", contentType) - res, err := api.makeRequestWithHeaders("PUT", uri, body, headers) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers) var r WorkerScriptResponse if err != nil { return r, err @@ -527,14 +528,14 @@ func (api *API) uploadWorkerForZone(zoneID, contentType string, body []byte) (Wo return r, nil } -func (api *API) uploadWorkerWithName(scriptName, contentType string, body []byte) (WorkerScriptResponse, error) { +func (api *API) uploadWorkerWithName(ctx context.Context, scriptName, contentType string, body []byte) (WorkerScriptResponse, error) { if api.AccountID == "" { return WorkerScriptResponse{}, errors.New("account ID required") } uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName headers := make(http.Header) headers.Set("Content-Type", contentType) - res, err := api.makeRequestWithHeaders("PUT", uri, body, headers) + res, err := api.makeRequestContextWithHeaders(ctx, http.MethodPut, uri, body, headers) var r WorkerScriptResponse if err != nil { return r, err @@ -620,14 +621,14 @@ func formatMultipartBody(params *WorkerScriptParams) (string, []byte, error) { // CreateWorkerRoute creates worker route for a zone // // API reference: https://api.cloudflare.com/#worker-filters-create-filter, https://api.cloudflare.com/#worker-routes-create-route -func (api *API) CreateWorkerRoute(zoneID string, route WorkerRoute) (WorkerRouteResponse, error) { +func (api *API) CreateWorkerRoute(ctx context.Context, zoneID string, route WorkerRoute) (WorkerRouteResponse, error) { pathComponent, err := getRouteEndpoint(api, route) if err != nil { return WorkerRouteResponse{}, err } uri := "/zones/" + zoneID + "/workers/" + pathComponent - res, err := api.makeRequest("POST", uri, route) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, route) if err != nil { return WorkerRouteResponse{}, err } @@ -642,9 +643,9 @@ func (api *API) CreateWorkerRoute(zoneID string, route WorkerRoute) (WorkerRoute // DeleteWorkerRoute deletes worker route for a zone // // API reference: https://api.cloudflare.com/#worker-routes-delete-route -func (api *API) DeleteWorkerRoute(zoneID string, routeID string) (WorkerRouteResponse, error) { +func (api *API) DeleteWorkerRoute(ctx context.Context, zoneID string, routeID string) (WorkerRouteResponse, error) { uri := "/zones/" + zoneID + "/workers/routes/" + routeID - res, err := api.makeRequest("DELETE", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil) if err != nil { return WorkerRouteResponse{}, err } @@ -659,7 +660,7 @@ func (api *API) DeleteWorkerRoute(zoneID string, routeID string) (WorkerRouteRes // ListWorkerRoutes returns list of worker routes // // API reference: https://api.cloudflare.com/#worker-filters-list-filters, https://api.cloudflare.com/#worker-routes-list-routes -func (api *API) ListWorkerRoutes(zoneID string) (WorkerRoutesResponse, error) { +func (api *API) ListWorkerRoutes(ctx context.Context, zoneID string) (WorkerRoutesResponse, error) { pathComponent := "filters" // Unfortunately we don't have a good signal of whether the user is wanting // to use the deprecated filters endpoint (https://api.cloudflare.com/#worker-filters-list-filters) @@ -674,7 +675,7 @@ func (api *API) ListWorkerRoutes(zoneID string) (WorkerRoutesResponse, error) { pathComponent = "routes" } uri := "/zones/" + zoneID + "/workers/" + pathComponent - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return WorkerRoutesResponse{}, err } @@ -698,13 +699,13 @@ func (api *API) ListWorkerRoutes(zoneID string) (WorkerRoutesResponse, error) { // UpdateWorkerRoute updates worker route for a zone. // // API reference: https://api.cloudflare.com/#worker-filters-update-filter, https://api.cloudflare.com/#worker-routes-update-route -func (api *API) UpdateWorkerRoute(zoneID string, routeID string, route WorkerRoute) (WorkerRouteResponse, error) { +func (api *API) UpdateWorkerRoute(ctx context.Context, zoneID string, routeID string, route WorkerRoute) (WorkerRouteResponse, error) { pathComponent, err := getRouteEndpoint(api, route) if err != nil { return WorkerRouteResponse{}, err } uri := "/zones/" + zoneID + "/workers/" + pathComponent + "/" + routeID - res, err := api.makeRequest("PUT", uri, route) + res, err := api.makeRequestContext(ctx, http.MethodPut, uri, route) if err != nil { return WorkerRouteResponse{}, err } diff --git a/workers_cron_triggers_test.go b/workers_cron_triggers_test.go index 8f910b61224..def78778d18 100644 --- a/workers_cron_triggers_test.go +++ b/workers_cron_triggers_test.go @@ -15,7 +15,7 @@ func TestListWorkerCronTriggers(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "GET", "Expected method 'GET', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodGet, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, @@ -53,7 +53,7 @@ func TestUpdateWorkerCronTriggers(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "PUT", "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPut, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprint(w, `{ "success": true, diff --git a/workers_example_test.go b/workers_example_test.go index 8831f9ce705..6b2c698616d 100644 --- a/workers_example_test.go +++ b/workers_example_test.go @@ -1,6 +1,7 @@ package cloudflare_test import ( + "context" "fmt" "log" @@ -22,7 +23,7 @@ func ExampleAPI_UploadWorker() { log.Fatal(err) } - res, err := api.UploadWorker(&cloudflare.WorkerRequestParams{ZoneID: zoneID}, workerScript) + res, err := api.UploadWorker(context.TODO(), &cloudflare.WorkerRequestParams{ZoneID: zoneID}, workerScript) if err != nil { log.Fatal(err) } @@ -37,7 +38,7 @@ func UploadWorkerWithName() { log.Fatal(err) } - res, err := api.UploadWorker(&cloudflare.WorkerRequestParams{ScriptName: "baz"}, workerScript) + res, err := api.UploadWorker(context.TODO(), &cloudflare.WorkerRequestParams{ScriptName: "baz"}, workerScript) if err != nil { log.Fatal(err) } @@ -55,7 +56,7 @@ func ExampleAPI_DownloadWorker() { log.Fatal(err) } - res, err := api.DownloadWorker(&cloudflare.WorkerRequestParams{ZoneID: zoneID}) + res, err := api.DownloadWorker(context.TODO(), &cloudflare.WorkerRequestParams{ZoneID: zoneID}) if err != nil { log.Fatal(err) } @@ -70,7 +71,7 @@ func DownloadWorkerWithName() { log.Fatal(err) } - res, err := api.DownloadWorker(&cloudflare.WorkerRequestParams{ScriptName: "baz"}) + res, err := api.DownloadWorker(context.TODO(), &cloudflare.WorkerRequestParams{ScriptName: "baz"}) if err != nil { log.Fatal(err) } @@ -87,7 +88,7 @@ func ExampleAPI_DeleteWorker() { if err != nil { log.Fatal(err) } - res, err := api.DeleteWorker(&cloudflare.WorkerRequestParams{ZoneID: zoneID}) + res, err := api.DeleteWorker(context.TODO(), &cloudflare.WorkerRequestParams{ZoneID: zoneID}) if err != nil { log.Fatal(err) } @@ -102,7 +103,7 @@ func DeleteWorkerWithName() { log.Fatal(err) } - res, err := api.DeleteWorker(&cloudflare.WorkerRequestParams{ScriptName: "baz"}) + res, err := api.DeleteWorker(context.TODO(), &cloudflare.WorkerRequestParams{ScriptName: "baz"}) if err != nil { log.Fatal(err) } @@ -115,7 +116,7 @@ func ExampleAPI_ListWorkerScripts() { log.Fatal(err) } - res, err := api.ListWorkerScripts() + res, err := api.ListWorkerScripts(context.TODO()) if err != nil { log.Fatal(err) } @@ -133,7 +134,7 @@ func ExampleAPI_CreateWorkerRoute() { log.Fatal(err) } route := cloudflare.WorkerRoute{Pattern: "app1.example.com/*", Enabled: true} - res, err := api.CreateWorkerRoute(zoneID, route) + res, err := api.CreateWorkerRoute(context.TODO(), zoneID, route) if err != nil { log.Fatal(err) } @@ -151,13 +152,13 @@ func ExampleAPI_UpdateWorkerRoute() { log.Fatal(err) } // pull from existing list of routes to perform update on - routesResponse, err := api.ListWorkerRoutes(zoneID) + routesResponse, err := api.ListWorkerRoutes(context.TODO(), zoneID) if err != nil { log.Fatal(err) } route := cloudflare.WorkerRoute{Pattern: "app2.example.com/*", Enabled: true} // update first route retrieved from the listWorkerRoutes call with details above - res, err := api.UpdateWorkerRoute(zoneID, routesResponse.Routes[0].ID, route) + res, err := api.UpdateWorkerRoute(context.TODO(), zoneID, routesResponse.Routes[0].ID, route) if err != nil { log.Fatal(err) } @@ -174,7 +175,7 @@ func ExampleAPI_ListWorkerRoutes() { if err != nil { log.Fatal(err) } - res, err := api.ListWorkerRoutes(zoneID) + res, err := api.ListWorkerRoutes(context.TODO(), zoneID) if err != nil { log.Fatal(err) } @@ -192,12 +193,12 @@ func ExampleAPI_DeleteWorkerRoute() { log.Fatal(err) } // pull from existing list of routes to perform delete on - routesResponse, err := api.ListWorkerRoutes(zoneID) + routesResponse, err := api.ListWorkerRoutes(context.TODO(), zoneID) if err != nil { log.Fatal(err) } // delete first route retrieved from the listWorkerRoutes call - res, err := api.DeleteWorkerRoute(zoneID, routesResponse.Routes[0].ID) + res, err := api.DeleteWorkerRoute(context.TODO(), zoneID, routesResponse.Routes[0].ID) if err != nil { log.Fatal(err) } diff --git a/workers_kv_test.go b/workers_kv_test.go index ef917232cca..d7566756ce8 100644 --- a/workers_kv_test.go +++ b/workers_kv_test.go @@ -27,7 +27,7 @@ func TestWorkersKV_CreateWorkersKVNamespace(t *testing.T) { }` mux.HandleFunc("/accounts/foo/storage/kv/namespaces", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -58,7 +58,7 @@ func TestWorkersKV_DeleteWorkersKVNamespace(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -97,18 +97,18 @@ func TestWorkersKV_ListWorkersKVNamespace(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces"), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) res, err := client.ListWorkersKVNamespaces(context.Background()) want := []WorkersKVNamespace{ - WorkersKVNamespace{ + { ID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", Title: "test_namespace_1", }, - WorkersKVNamespace{ + { ID: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", Title: "test_namespace_2", }, @@ -166,7 +166,7 @@ func TestWorkersKV_ListWorkersKVNamespaceMultiplePages(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces"), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") if r.URL.Query().Get("page") == "1" { @@ -182,11 +182,11 @@ func TestWorkersKV_ListWorkersKVNamespaceMultiplePages(t *testing.T) { res, err := client.ListWorkersKVNamespaces(context.Background()) want := []WorkersKVNamespace{ - WorkersKVNamespace{ + { ID: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", Title: "test_namespace_1", }, - WorkersKVNamespace{ + { ID: "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", Title: "test_namespace_2", }, @@ -216,7 +216,7 @@ func TestWorkersKV_UpdateWorkersKVNamespace(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -244,7 +244,7 @@ func TestWorkersKV_WriteWorkersKV(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/values/%s", namespace, key), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/octet-stream") fmt.Fprintf(w, response) }) @@ -272,7 +272,7 @@ func TestWorkersKV_WriteWorkersKVBulk(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/bulk", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, response) }) @@ -291,7 +291,7 @@ func TestWorkersKV_ReadWorkersKV(t *testing.T) { namespace := "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/values/%s", namespace, key), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "text/plain") fmt.Fprintf(w, "test_value") }) @@ -318,7 +318,7 @@ func TestWorkersKV_DeleteWorkersKV(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/values/%s", namespace, key), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -346,7 +346,7 @@ func TestWorkersKV_DeleteWorkersKVBulk(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/bulk", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, response) }) @@ -380,7 +380,7 @@ func TestWorkersKV_ListStorageKeys(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/keys", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -450,7 +450,7 @@ func TestWorkersKV_ListStorageKeysWithOptions(t *testing.T) { }` mux.HandleFunc(fmt.Sprintf("/accounts/foo/storage/kv/namespaces/%s/keys", namespace), func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) diff --git a/workers_secrets_test.go b/workers_secrets_test.go index d47dc3e8ba2..09ee3f42a12 100644 --- a/workers_secrets_test.go +++ b/workers_secrets_test.go @@ -24,7 +24,7 @@ func TestWorkers_SetWorkersSecret(t *testing.T) { }` mux.HandleFunc("/accounts/foo/workers/scripts/test-script/secrets", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -61,7 +61,7 @@ func TestWorkers_DeleteWorkersSecret(t *testing.T) { }` mux.HandleFunc("/accounts/foo/workers/scripts/test-script/secrets/my-secret", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) @@ -89,7 +89,7 @@ func TestWorkers_ListWorkersSecret(t *testing.T) { }` mux.HandleFunc("/accounts/foo/workers/scripts/test-script/secrets", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, response) }) diff --git a/workers_test.go b/workers_test.go index 78cee170236..8716272e87c 100644 --- a/workers_test.go +++ b/workers_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "encoding/json" "fmt" "io/ioutil" @@ -230,11 +231,11 @@ func TestWorkers_DeleteWorker(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/script", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, deleteWorkerResponseData) }) - res, err := client.DeleteWorker(&WorkerRequestParams{ZoneID: "foo"}) + res, err := client.DeleteWorker(context.TODO(), &WorkerRequestParams{ZoneID: "foo"}) want := WorkerScriptResponse{ successResponse, WorkerScript{}} @@ -248,11 +249,11 @@ func TestWorkers_DeleteWorkerWithName(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/foo/workers/scripts/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, deleteWorkerResponseData) }) - res, err := client.DeleteWorker(&WorkerRequestParams{ScriptName: "bar"}) + res, err := client.DeleteWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}) want := WorkerScriptResponse{ successResponse, WorkerScript{}} @@ -265,7 +266,7 @@ func TestWorkers_DeleteWorkerWithNameErrorsWithoutAccountId(t *testing.T) { setup() defer teardown() - _, err := client.DeleteWorker(&WorkerRequestParams{ScriptName: "bar"}) + _, err := client.DeleteWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}) assert.Error(t, err) } @@ -274,11 +275,11 @@ func TestWorkers_DownloadWorker(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/script", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, workerScript) }) - res, err := client.DownloadWorker(&WorkerRequestParams{ZoneID: "foo"}) + res, err := client.DownloadWorker(context.TODO(), &WorkerRequestParams{ZoneID: "foo"}) want := WorkerScriptResponse{ successResponse, WorkerScript{ @@ -294,11 +295,11 @@ func TestWorkers_DownloadWorkerWithName(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/foo/workers/scripts/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/javascript") fmt.Fprintf(w, workerScript) }) - res, err := client.DownloadWorker(&WorkerRequestParams{ScriptName: "bar"}) + res, err := client.DownloadWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}) want := WorkerScriptResponse{ successResponse, WorkerScript{ @@ -313,7 +314,7 @@ func TestWorkers_DownloadWorkerWithNameErrorsWithoutAccountId(t *testing.T) { setup() defer teardown() - _, err := client.DownloadWorker(&WorkerRequestParams{ScriptName: "bar"}) + _, err := client.DownloadWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}) assert.Error(t, err) } @@ -322,12 +323,12 @@ func TestWorkers_ListWorkerScripts(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/foo/workers/scripts", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, listWorkersResponseData) }) - res, err := client.ListWorkerScripts() + res, err := client.ListWorkerScripts(context.TODO()) sampleDate, _ := time.Parse(time.RFC3339Nano, "2018-04-22T17:10:48.938097Z") want := []WorkerMetaData{ { @@ -353,13 +354,13 @@ func TestWorkers_UploadWorker(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/script", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) contentTypeHeader := r.Header.Get("content-type") assert.Equal(t, "application/javascript", contentTypeHeader, "Expected content-type request header to be 'application/javascript', got %s", contentTypeHeader) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, uploadWorkerResponseData) }) - res, err := client.UploadWorker(&WorkerRequestParams{ZoneID: "foo"}, workerScript) + res, err := client.UploadWorker(context.TODO(), &WorkerRequestParams{ZoneID: "foo"}, workerScript) formattedTime, _ := time.Parse(time.RFC3339Nano, "2018-06-09T15:17:01.989141Z") want := WorkerScriptResponse{ successResponse, @@ -381,13 +382,13 @@ func TestWorkers_UploadWorkerWithName(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/foo/workers/scripts/bar", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) contentTypeHeader := r.Header.Get("content-type") assert.Equal(t, "application/javascript", contentTypeHeader, "Expected content-type request header to be 'application/javascript', got %s", contentTypeHeader) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, uploadWorkerResponseData) }) - res, err := client.UploadWorker(&WorkerRequestParams{ScriptName: "bar"}, workerScript) + res, err := client.UploadWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, workerScript) formattedTime, _ := time.Parse(time.RFC3339Nano, "2018-06-09T15:17:01.989141Z") want := WorkerScriptResponse{ successResponse, @@ -409,13 +410,13 @@ func TestWorkers_UploadWorkerSingleScriptWithAccount(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/script", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) contentTypeHeader := r.Header.Get("content-type") assert.Equal(t, "application/javascript", contentTypeHeader, "Expected content-type request header to be 'application/javascript', got %s", contentTypeHeader) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, uploadWorkerResponseData) }) - res, err := client.UploadWorker(&WorkerRequestParams{ZoneID: "foo"}, workerScript) + res, err := client.UploadWorker(context.TODO(), &WorkerRequestParams{ZoneID: "foo"}, workerScript) formattedTime, _ := time.Parse(time.RFC3339Nano, "2018-06-09T15:17:01.989141Z") want := WorkerScriptResponse{ successResponse, @@ -436,7 +437,7 @@ func TestWorkers_UploadWorkerWithNameErrorsWithoutAccountId(t *testing.T) { setup() defer teardown() - _, err := client.UploadWorker(&WorkerRequestParams{ScriptName: "bar"}, workerScript) + _, err := client.UploadWorker(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, workerScript) assert.Error(t, err) } @@ -446,7 +447,7 @@ func TestWorkers_UploadWorkerWithInheritBinding(t *testing.T) { // Setup route handler for both single-script and multi-script handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) mpUpload, err := parseMultipartUpload(r) assert.NoError(t, err) @@ -495,13 +496,13 @@ func TestWorkers_UploadWorkerWithInheritBinding(t *testing.T) { }} // Test single-script - res, err := client.UploadWorkerWithBindings(&WorkerRequestParams{ZoneID: "foo"}, &scriptParams) + res, err := client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ZoneID: "foo"}, &scriptParams) if assert.NoError(t, err) { assert.Equal(t, want, res) } // Test multi-script - res, err = client.UploadWorkerWithBindings(&WorkerRequestParams{ScriptName: "bar"}, &scriptParams) + res, err = client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, &scriptParams) if assert.NoError(t, err) { assert.Equal(t, want, res) } @@ -512,7 +513,7 @@ func TestWorkers_UploadWorkerWithKVBinding(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) mpUpload, err := parseMultipartUpload(r) assert.NoError(t, err) @@ -540,7 +541,7 @@ func TestWorkers_UploadWorkerWithKVBinding(t *testing.T) { }, }, } - _, err := client.UploadWorkerWithBindings(&WorkerRequestParams{ScriptName: "bar"}, &scriptParams) + _, err := client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, &scriptParams) assert.NoError(t, err) } @@ -549,7 +550,7 @@ func TestWorkers_UploadWorkerWithWasmBinding(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) mpUpload, err := parseMultipartUpload(r) assert.NoError(t, err) @@ -582,7 +583,7 @@ func TestWorkers_UploadWorkerWithWasmBinding(t *testing.T) { }, }, } - _, err := client.UploadWorkerWithBindings(&WorkerRequestParams{ScriptName: "bar"}, &scriptParams) + _, err := client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, &scriptParams) assert.NoError(t, err) } @@ -591,7 +592,7 @@ func TestWorkers_UploadWorkerWithPlainTextBinding(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) mpUpload, err := parseMultipartUpload(r) assert.NoError(t, err) @@ -619,7 +620,7 @@ func TestWorkers_UploadWorkerWithPlainTextBinding(t *testing.T) { }, }, } - _, err := client.UploadWorkerWithBindings(&WorkerRequestParams{ScriptName: "bar"}, &scriptParams) + _, err := client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, &scriptParams) assert.NoError(t, err) } @@ -628,7 +629,7 @@ func TestWorkers_UploadWorkerWithSecretTextBinding(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) mpUpload, err := parseMultipartUpload(r) assert.NoError(t, err) @@ -656,7 +657,7 @@ func TestWorkers_UploadWorkerWithSecretTextBinding(t *testing.T) { }, }, } - _, err := client.UploadWorkerWithBindings(&WorkerRequestParams{ScriptName: "bar"}, &scriptParams) + _, err := client.UploadWorkerWithBindings(context.TODO(), &WorkerRequestParams{ScriptName: "bar"}, &scriptParams) assert.NoError(t, err) } @@ -665,12 +666,12 @@ func TestWorkers_CreateWorkerRoute(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/filters", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, createWorkerRouteResponse) }) route := WorkerRoute{Pattern: "app1.example.com/*", Enabled: true} - res, err := client.CreateWorkerRoute("foo", route) + res, err := client.CreateWorkerRoute(context.TODO(), "foo", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ID: "e7a57d8746e74ae49c25994dadb421b1"}} if assert.NoError(t, err) { assert.Equal(t, want, res) @@ -682,12 +683,12 @@ func TestWorkers_CreateWorkerRouteEnt(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/routes", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, createWorkerRouteResponse) }) route := WorkerRoute{Pattern: "app1.example.com/*", Script: "test_script"} - res, err := client.CreateWorkerRoute("foo", route) + res, err := client.CreateWorkerRoute(context.TODO(), "foo", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ID: "e7a57d8746e74ae49c25994dadb421b1"}} if assert.NoError(t, err) { assert.Equal(t, want, res) @@ -699,12 +700,12 @@ func TestWorkers_CreateWorkerRouteSingleScriptWithAccount(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/filters", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, createWorkerRouteResponse) }) route := WorkerRoute{Pattern: "app1.example.com/*", Enabled: true} - res, err := client.CreateWorkerRoute("foo", route) + res, err := client.CreateWorkerRoute(context.TODO(), "foo", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ID: "e7a57d8746e74ae49c25994dadb421b1"}} if assert.NoError(t, err) { assert.Equal(t, want, res) @@ -716,7 +717,7 @@ func TestWorkers_CreateWorkerRouteErrorsWhenMixingSingleAndMultiScriptProperties defer teardown() route := WorkerRoute{Pattern: "app1.example.com/*", Script: "test_script", Enabled: true} - _, err := client.CreateWorkerRoute("foo", route) + _, err := client.CreateWorkerRoute(context.TODO(), "foo", route) assert.EqualError(t, err, "Only `Script` or `Enabled` may be specified for a WorkerRoute, not both") } @@ -724,13 +725,13 @@ func TestWorkers_CreateWorkerRouteWithNoScript(t *testing.T) { setup(UsingAccount("foo")) mux.HandleFunc("/zones/foo/workers/routes", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "POST", r.Method, "Expected method 'POST', got %s", r.Method) + assert.Equal(t, http.MethodPost, r.Method, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, createWorkerRouteResponse) }) route := WorkerRoute{Pattern: "app1.example.com/*"} - _, err := client.CreateWorkerRoute("foo", route) + _, err := client.CreateWorkerRoute(context.TODO(), "foo", route) assert.NoError(t, err) } @@ -739,11 +740,11 @@ func TestWorkers_DeleteWorkerRoute(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/routes/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, deleteWorkerRouteResponseData) }) - res, err := client.DeleteWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1") + res, err := client.DeleteWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1") want := WorkerRouteResponse{successResponse, WorkerRoute{ ID: "e7a57d8746e74ae49c25994dadb421b1", @@ -758,11 +759,11 @@ func TestWorkers_DeleteWorkerRouteEnt(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/routes/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, deleteWorkerRouteResponseData) }) - res, err := client.DeleteWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1") + res, err := client.DeleteWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1") want := WorkerRouteResponse{successResponse, WorkerRoute{ ID: "e7a57d8746e74ae49c25994dadb421b1", @@ -777,12 +778,12 @@ func TestWorkers_ListWorkerRoutes(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/filters", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, listRouteResponseData) }) - res, err := client.ListWorkerRoutes("foo") + res, err := client.ListWorkerRoutes(context.TODO(), "foo") want := WorkerRoutesResponse{successResponse, []WorkerRoute{ {ID: "e7a57d8746e74ae49c25994dadb421b1", Pattern: "app1.example.com/*", Enabled: true}, @@ -799,12 +800,12 @@ func TestWorkers_ListWorkerRoutesEnt(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/routes", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, listRouteEntResponseData) }) - res, err := client.ListWorkerRoutes("foo") + res, err := client.ListWorkerRoutes(context.TODO(), "foo") want := WorkerRoutesResponse{successResponse, []WorkerRoute{ {ID: "e7a57d8746e74ae49c25994dadb421b1", Pattern: "app1.example.com/*", Script: "test_script_1", Enabled: true}, @@ -822,12 +823,12 @@ func TestWorkers_UpdateWorkerRoute(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/filters/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, updateWorkerRouteResponse) }) route := WorkerRoute{Pattern: "app3.example.com/*", Enabled: true} - res, err := client.UpdateWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1", route) + res, err := client.UpdateWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ ID: "e7a57d8746e74ae49c25994dadb421b1", @@ -844,12 +845,12 @@ func TestWorkers_UpdateWorkerRouteEnt(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/routes/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, updateWorkerRouteEntResponse) }) route := WorkerRoute{Pattern: "app3.example.com/*", Script: "test_script_1"} - res, err := client.UpdateWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1", route) + res, err := client.UpdateWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ ID: "e7a57d8746e74ae49c25994dadb421b1", @@ -866,12 +867,12 @@ func TestWorkers_UpdateWorkerRouteSingleScriptWithAccount(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/workers/filters/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, updateWorkerRouteEntResponse) }) route := WorkerRoute{Pattern: "app3.example.com/*", Enabled: true} - res, err := client.UpdateWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1", route) + res, err := client.UpdateWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1", route) want := WorkerRouteResponse{successResponse, WorkerRoute{ ID: "e7a57d8746e74ae49c25994dadb421b1", @@ -888,18 +889,18 @@ func TestWorkers_ListWorkerBindingsMultiScript(t *testing.T) { defer teardown() mux.HandleFunc("/accounts/foo/workers/scripts/my-script/bindings", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, listBindingsResponseData) }) mux.HandleFunc("/accounts/foo/workers/scripts/my-script/bindings/MY_WASM/content", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/wasm") _, _ = w.Write([]byte("mock multi-script wasm")) }) - res, err := client.ListWorkerBindings(&WorkerRequestParams{ + res, err := client.ListWorkerBindings(context.TODO(), &WorkerRequestParams{ ScriptName: "my-script", }) assert.NoError(t, err) @@ -948,7 +949,7 @@ func TestWorkers_UpdateWorkerRouteErrorsWhenMixingSingleAndMultiScriptProperties defer teardown() route := WorkerRoute{Pattern: "app1.example.com/*", Script: "test_script", Enabled: true} - _, err := client.UpdateWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1", route) + _, err := client.UpdateWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1", route) assert.EqualError(t, err, "Only `Script` or `Enabled` may be specified for a WorkerRoute, not both") } @@ -956,12 +957,12 @@ func TestWorkers_UpdateWorkerRouteWithNoScript(t *testing.T) { setup(UsingAccount("foo")) mux.HandleFunc("/zones/foo/workers/routes/e7a57d8746e74ae49c25994dadb421b1", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "PUT", r.Method, "Expected method 'PUT', got %s", r.Method) + assert.Equal(t, http.MethodPut, r.Method, "Expected method 'PUT', got %s", r.Method) w.Header().Set("content-type", "application-json") fmt.Fprintf(w, updateWorkerRouteEntResponse) }) route := WorkerRoute{Pattern: "app1.example.com/*"} - _, err := client.UpdateWorkerRoute("foo", "e7a57d8746e74ae49c25994dadb421b1", route) + _, err := client.UpdateWorkerRoute(context.TODO(), "foo", "e7a57d8746e74ae49c25994dadb421b1", route) assert.NoError(t, err) } diff --git a/zone.go b/zone.go index 8f138e25291..afac5170bb7 100644 --- a/zone.go +++ b/zone.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "net/http" "net/url" "strconv" "sync" @@ -306,7 +307,7 @@ type zoneSubscriptionRatePlanPayload struct { // This will add the new zone to the specified multi-user account. // // API reference: https://api.cloudflare.com/#zone-create-a-zone -func (api *API) CreateZone(name string, jumpstart bool, account Account, zoneType string) (Zone, error) { +func (api *API) CreateZone(ctx context.Context, name string, jumpstart bool, account Account, zoneType string) (Zone, error) { var newzone newZone newzone.Name = name newzone.JumpStart = jumpstart @@ -320,7 +321,7 @@ func (api *API) CreateZone(name string, jumpstart bool, account Account, zoneTyp newzone.Type = "full" } - res, err := api.makeRequest("POST", "/zones", newzone) + res, err := api.makeRequestContext(ctx, http.MethodPost, "/zones", newzone) if err != nil { return Zone{}, err } @@ -336,8 +337,8 @@ func (api *API) CreateZone(name string, jumpstart bool, account Account, zoneTyp // ZoneActivationCheck initiates another zone activation check for newly-created zones. // // API reference: https://api.cloudflare.com/#zone-initiate-another-zone-activation-check -func (api *API) ZoneActivationCheck(zoneID string) (Response, error) { - res, err := api.makeRequest("PUT", "/zones/"+zoneID+"/activation_check", nil) +func (api *API) ZoneActivationCheck(ctx context.Context, zoneID string) (Response, error) { + res, err := api.makeRequestContext(ctx, http.MethodPut, "/zones/"+zoneID+"/activation_check", nil) if err != nil { return Response{}, err } @@ -353,7 +354,7 @@ func (api *API) ZoneActivationCheck(zoneID string) (Response, error) { // to filter against. // // API reference: https://api.cloudflare.com/#zone-list-zones -func (api *API) ListZones(z ...string) ([]Zone, error) { +func (api *API) ListZones(ctx context.Context, z ...string) ([]Zone, error) { v := url.Values{} var res []byte @@ -363,7 +364,7 @@ func (api *API) ListZones(z ...string) ([]Zone, error) { if len(z) > 0 { for _, zone := range z { v.Set("name", normalizeZoneName(zone)) - res, err = api.makeRequest("GET", "/zones?"+v.Encode(), nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, "/zones?"+v.Encode(), nil) if err != nil { return []Zone{}, err } @@ -380,7 +381,7 @@ func (api *API) ListZones(z ...string) ([]Zone, error) { } } } else { - res, err = api.makeRequest("GET", "/zones?per_page=50", nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, "/zones?per_page=50", nil) if err != nil { return []Zone{}, err } @@ -396,7 +397,7 @@ func (api *API) ListZones(z ...string) ([]Zone, error) { for i := 1; i <= totalPageCount; i++ { go func(pageNumber int) error { - res, err = api.makeRequest("GET", fmt.Sprintf("/zones?per_page=50&page=%d", pageNumber), nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, fmt.Sprintf("/zones?per_page=50&page=%d", pageNumber), nil) if err != nil { errc <- err } @@ -442,7 +443,7 @@ func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r Zone opt.params.Add("per_page", "50") - res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, "/zones?"+opt.params.Encode(), nil) if err != nil { return ZonesResponse{}, err } @@ -459,7 +460,7 @@ func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r Zone for i := 1; i <= totalPageCount; i++ { go func(pageNumber int) error { opt.params.Set("page", strconv.Itoa(pageNumber)) - res, err = api.makeRequestContext(ctx, "GET", "/zones?"+opt.params.Encode(), nil) + res, err = api.makeRequestContext(ctx, http.MethodGet, "/zones?"+opt.params.Encode(), nil) if err != nil { errc <- err } @@ -494,8 +495,8 @@ func (api *API) ListZonesContext(ctx context.Context, opts ...ReqOption) (r Zone // ZoneDetails fetches information about a zone. // // API reference: https://api.cloudflare.com/#zone-zone-details -func (api *API) ZoneDetails(zoneID string) (Zone, error) { - res, err := api.makeRequest("GET", "/zones/"+zoneID, nil) +func (api *API) ZoneDetails(ctx context.Context, zoneID string) (Zone, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID, nil) if err != nil { return Zone{}, err } @@ -516,9 +517,9 @@ type ZoneOptions struct { // ZoneSetPaused pauses Cloudflare service for the entire zone, sending all // traffic direct to the origin. -func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) { +func (api *API) ZoneSetPaused(ctx context.Context, zoneID string, paused bool) (Zone, error) { zoneopts := ZoneOptions{Paused: &paused} - zone, err := api.EditZone(zoneID, zoneopts) + zone, err := api.EditZone(ctx, zoneID, zoneopts) if err != nil { return Zone{}, err } @@ -528,9 +529,9 @@ func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) { // ZoneSetVanityNS sets custom nameservers for the zone. // These names must be within the same zone. -func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) { +func (api *API) ZoneSetVanityNS(ctx context.Context, zoneID string, ns []string) (Zone, error) { zoneopts := ZoneOptions{VanityNS: ns} - zone, err := api.EditZone(zoneID, zoneopts) + zone, err := api.EditZone(ctx, zoneID, zoneopts) if err != nil { return Zone{}, err } @@ -544,13 +545,13 @@ func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) { // "CF_ENT". // // API reference: https://api.cloudflare.com/#zone-subscription-create-zone-subscription -func (api *API) ZoneSetPlan(zoneID string, planType string) error { +func (api *API) ZoneSetPlan(ctx context.Context, zoneID string, planType string) error { zonePayload := zoneSubscriptionRatePlanPayload{} zonePayload.RatePlan.ID = planType uri := fmt.Sprintf("/zones/%s/subscription", zoneID) - _, err := api.makeRequest("POST", uri, zonePayload) + _, err := api.makeRequestContext(ctx, http.MethodPost, uri, zonePayload) if err != nil { return err } @@ -564,13 +565,13 @@ func (api *API) ZoneSetPlan(zoneID string, planType string) error { // "CF_ENT". // // API reference: https://api.cloudflare.com/#zone-subscription-update-zone-subscription -func (api *API) ZoneUpdatePlan(zoneID string, planType string) error { +func (api *API) ZoneUpdatePlan(ctx context.Context, zoneID string, planType string) error { zonePayload := zoneSubscriptionRatePlanPayload{} zonePayload.RatePlan.ID = planType uri := fmt.Sprintf("/zones/%s/subscription", zoneID) - _, err := api.makeRequest("PUT", uri, zonePayload) + _, err := api.makeRequestContext(ctx, http.MethodPut, uri, zonePayload) if err != nil { return err } @@ -583,8 +584,8 @@ func (api *API) ZoneUpdatePlan(zoneID string, planType string) error { // This is usually called by ZoneSetPaused or ZoneSetVanityNS. // // API reference: https://api.cloudflare.com/#zone-edit-zone-properties -func (api *API) EditZone(zoneID string, zoneOpts ZoneOptions) (Zone, error) { - res, err := api.makeRequest("PATCH", "/zones/"+zoneID, zoneOpts) +func (api *API) EditZone(ctx context.Context, zoneID string, zoneOpts ZoneOptions) (Zone, error) { + res, err := api.makeRequestContext(ctx, "PATCH", "/zones/"+zoneID, zoneOpts) if err != nil { return Zone{}, err } @@ -603,9 +604,9 @@ func (api *API) EditZone(zoneID string, zoneOpts ZoneOptions) (Zone, error) { // zone if there is a high cached vs. uncached request ratio. // // API reference: https://api.cloudflare.com/#zone-purge-all-files -func (api *API) PurgeEverything(zoneID string) (PurgeCacheResponse, error) { +func (api *API) PurgeEverything(ctx context.Context, zoneID string) (PurgeCacheResponse, error) { uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequest("POST", uri, PurgeCacheRequest{true, nil, nil, nil}) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, PurgeCacheRequest{true, nil, nil, nil}) if err != nil { return PurgeCacheResponse{}, err } @@ -620,8 +621,8 @@ func (api *API) PurgeEverything(zoneID string) (PurgeCacheResponse, error) { // PurgeCache purges the cache using the given PurgeCacheRequest (zone/url/tag). // // API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags -func (api *API) PurgeCache(zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { - return api.PurgeCacheContext(context.TODO(), zoneID, pcr) +func (api *API) PurgeCache(ctx context.Context, zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { + return api.PurgeCacheContext(ctx, zoneID, pcr) } // PurgeCacheContext purges the cache using the given PurgeCacheRequest (zone/url/tag). @@ -629,7 +630,7 @@ func (api *API) PurgeCache(zoneID string, pcr PurgeCacheRequest) (PurgeCacheResp // API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags func (api *API) PurgeCacheContext(ctx context.Context, zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequestContext(ctx, "POST", uri, pcr) + res, err := api.makeRequestContext(ctx, http.MethodPost, uri, pcr) if err != nil { return PurgeCacheResponse{}, err } @@ -644,8 +645,8 @@ func (api *API) PurgeCacheContext(ctx context.Context, zoneID string, pcr PurgeC // DeleteZone deletes the given zone. // // API reference: https://api.cloudflare.com/#zone-delete-a-zone -func (api *API) DeleteZone(zoneID string) (ZoneID, error) { - res, err := api.makeRequest("DELETE", "/zones/"+zoneID, nil) +func (api *API) DeleteZone(ctx context.Context, zoneID string) (ZoneID, error) { + res, err := api.makeRequestContext(ctx, http.MethodDelete, "/zones/"+zoneID, nil) if err != nil { return ZoneID{}, err } @@ -660,9 +661,9 @@ func (api *API) DeleteZone(zoneID string) (ZoneID, error) { // AvailableZoneRatePlans returns information about all plans available to the specified zone. // // API reference: https://api.cloudflare.com/#zone-plan-available-plans -func (api *API) AvailableZoneRatePlans(zoneID string) ([]ZoneRatePlan, error) { +func (api *API) AvailableZoneRatePlans(ctx context.Context, zoneID string) ([]ZoneRatePlan, error) { uri := "/zones/" + zoneID + "/available_rate_plans" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []ZoneRatePlan{}, err } @@ -677,9 +678,9 @@ func (api *API) AvailableZoneRatePlans(zoneID string) ([]ZoneRatePlan, error) { // AvailableZonePlans returns information about all plans available to the specified zone. // // API reference: https://api.cloudflare.com/#zone-rate-plan-list-available-plans -func (api *API) AvailableZonePlans(zoneID string) ([]ZonePlan, error) { +func (api *API) AvailableZonePlans(ctx context.Context, zoneID string) ([]ZonePlan, error) { uri := "/zones/" + zoneID + "/available_plans" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return []ZonePlan{}, err } @@ -709,9 +710,9 @@ func (o ZoneAnalyticsOptions) encode() string { // ZoneAnalyticsDashboard returns zone analytics information. // // API reference: https://api.cloudflare.com/#zone-analytics-dashboard -func (api *API) ZoneAnalyticsDashboard(zoneID string, options ZoneAnalyticsOptions) (ZoneAnalyticsData, error) { +func (api *API) ZoneAnalyticsDashboard(ctx context.Context, zoneID string, options ZoneAnalyticsOptions) (ZoneAnalyticsData, error) { uri := "/zones/" + zoneID + "/analytics/dashboard" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ZoneAnalyticsData{}, err } @@ -726,9 +727,9 @@ func (api *API) ZoneAnalyticsDashboard(zoneID string, options ZoneAnalyticsOptio // ZoneAnalyticsByColocation returns zone analytics information by datacenter. // // API reference: https://api.cloudflare.com/#zone-analytics-analytics-by-co-locations -func (api *API) ZoneAnalyticsByColocation(zoneID string, options ZoneAnalyticsOptions) ([]ZoneAnalyticsColocation, error) { +func (api *API) ZoneAnalyticsByColocation(ctx context.Context, zoneID string, options ZoneAnalyticsOptions) ([]ZoneAnalyticsColocation, error) { uri := "/zones/" + zoneID + "/analytics/colos" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -743,9 +744,9 @@ func (api *API) ZoneAnalyticsByColocation(zoneID string, options ZoneAnalyticsOp // ZoneSettings returns all of the settings for a given zone. // // API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSettings(zoneID string) (*ZoneSettingResponse, error) { +func (api *API) ZoneSettings(ctx context.Context, zoneID string) (*ZoneSettingResponse, error) { uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return nil, err } @@ -762,9 +763,9 @@ func (api *API) ZoneSettings(zoneID string) (*ZoneSettingResponse, error) { // UpdateZoneSettings updates the settings for a given zone. // // API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSettings(zoneID string, settings []ZoneSetting) (*ZoneSettingResponse, error) { +func (api *API) UpdateZoneSettings(ctx context.Context, zoneID string, settings []ZoneSetting) (*ZoneSettingResponse, error) { uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("PATCH", uri, struct { + res, err := api.makeRequestContext(ctx, "PATCH", uri, struct { Items []ZoneSetting `json:"items"` }{settings}) if err != nil { @@ -783,9 +784,9 @@ func (api *API) UpdateZoneSettings(zoneID string, settings []ZoneSetting) (*Zone // ZoneSSLSettings returns information about SSL setting to the specified zone. // // API reference: https://api.cloudflare.com/#zone-settings-get-ssl-setting -func (api *API) ZoneSSLSettings(zoneID string) (ZoneSSLSetting, error) { +func (api *API) ZoneSSLSettings(ctx context.Context, zoneID string) (ZoneSSLSetting, error) { uri := "/zones/" + zoneID + "/settings/ssl" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ZoneSSLSetting{}, err } @@ -800,9 +801,9 @@ func (api *API) ZoneSSLSettings(zoneID string) (ZoneSSLSetting, error) { // FallbackOrigin returns information about the fallback origin for the specified zone. // // API reference: https://developers.cloudflare.com/ssl/ssl-for-saas/api-calls/#fallback-origin-configuration -func (api *API) FallbackOrigin(zoneID string) (FallbackOrigin, error) { +func (api *API) FallbackOrigin(ctx context.Context, zoneID string) (FallbackOrigin, error) { uri := "/zones/" + zoneID + "/fallback_origin" - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return FallbackOrigin{}, err } @@ -819,9 +820,9 @@ func (api *API) FallbackOrigin(zoneID string) (FallbackOrigin, error) { // UpdateFallbackOrigin updates the fallback origin for a given zone. // // API reference: https://developers.cloudflare.com/ssl/ssl-for-saas/api-calls/#4-example-patch-to-change-fallback-origin -func (api *API) UpdateFallbackOrigin(zoneID string, fbo FallbackOrigin) (*FallbackOriginResponse, error) { +func (api *API) UpdateFallbackOrigin(ctx context.Context, zoneID string, fbo FallbackOrigin) (*FallbackOriginResponse, error) { uri := "/zones/" + zoneID + "/fallback_origin" - res, err := api.makeRequest("PATCH", uri, fbo) + res, err := api.makeRequestContext(ctx, "PATCH", uri, fbo) if err != nil { return nil, err } @@ -851,9 +852,9 @@ func normalizeZoneName(name string) string { // ZoneSingleSetting returns information about specified setting to the specified zone. // // API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSingleSetting(zoneID, settingName string) (ZoneSetting, error) { +func (api *API) ZoneSingleSetting(ctx context.Context, zoneID, settingName string) (ZoneSetting, error) { uri := "/zones/" + zoneID + "/settings/" + settingName - res, err := api.makeRequest("GET", uri, nil) + res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil) if err != nil { return ZoneSetting{}, err } @@ -868,9 +869,9 @@ func (api *API) ZoneSingleSetting(zoneID, settingName string) (ZoneSetting, erro // UpdateZoneSingleSetting updates the specified setting for a given zone. // // API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSingleSetting(zoneID, settingName string, setting ZoneSetting) (*ZoneSettingSingleResponse, error) { +func (api *API) UpdateZoneSingleSetting(ctx context.Context, zoneID, settingName string, setting ZoneSetting) (*ZoneSettingSingleResponse, error) { uri := "/zones/" + zoneID + "/settings/" + settingName - res, err := api.makeRequest("PATCH", uri, setting) + res, err := api.makeRequestContext(ctx, "PATCH", uri, setting) if err != nil { return nil, err } @@ -887,8 +888,8 @@ func (api *API) UpdateZoneSingleSetting(zoneID, settingName string, setting Zone // ZoneExport returns the text BIND config for the given zone // // API reference: https://api.cloudflare.com/#dns-records-for-a-zone-export-dns-records -func (api *API) ZoneExport(zoneID string) (string, error) { - res, err := api.makeRequest("GET", "/zones/"+zoneID+"/dns_records/export", nil) +func (api *API) ZoneExport(ctx context.Context, zoneID string) (string, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID+"/dns_records/export", nil) if err != nil { return "", err } @@ -919,8 +920,8 @@ type ZoneDNSSEC struct { // ZoneDNSSECSetting returns the DNSSEC details of a zone // // API reference: https://api.cloudflare.com/#dnssec-dnssec-details -func (api *API) ZoneDNSSECSetting(zoneID string) (ZoneDNSSEC, error) { - res, err := api.makeRequest("GET", "/zones/"+zoneID+"/dnssec", nil) +func (api *API) ZoneDNSSECSetting(ctx context.Context, zoneID string) (ZoneDNSSEC, error) { + res, err := api.makeRequestContext(ctx, http.MethodGet, "/zones/"+zoneID+"/dnssec", nil) if err != nil { return ZoneDNSSEC{}, err } @@ -942,8 +943,8 @@ type ZoneDNSSECDeleteResponse struct { // DeleteZoneDNSSEC deletes DNSSEC for zone // // API reference: https://api.cloudflare.com/#dnssec-delete-dnssec-records -func (api *API) DeleteZoneDNSSEC(zoneID string) (string, error) { - res, err := api.makeRequest("DELETE", "/zones/"+zoneID+"/dnssec", nil) +func (api *API) DeleteZoneDNSSEC(ctx context.Context, zoneID string) (string, error) { + res, err := api.makeRequestContext(ctx, http.MethodDelete, "/zones/"+zoneID+"/dnssec", nil) if err != nil { return "", err } @@ -963,8 +964,8 @@ type ZoneDNSSECUpdateOptions struct { // UpdateZoneDNSSEC updates DNSSEC for a zone // // API reference: https://api.cloudflare.com/#dnssec-edit-dnssec-status -func (api *API) UpdateZoneDNSSEC(zoneID string, options ZoneDNSSECUpdateOptions) (ZoneDNSSEC, error) { - res, err := api.makeRequest("PATCH", "/zones/"+zoneID+"/dnssec", options) +func (api *API) UpdateZoneDNSSEC(ctx context.Context, zoneID string, options ZoneDNSSECUpdateOptions) (ZoneDNSSEC, error) { + res, err := api.makeRequestContext(ctx, "PATCH", "/zones/"+zoneID+"/dnssec", options) if err != nil { return ZoneDNSSEC{}, err } diff --git a/zone_example_test.go b/zone_example_test.go index 87699662a72..ac2b67eefae 100644 --- a/zone_example_test.go +++ b/zone_example_test.go @@ -4,6 +4,8 @@ import ( "fmt" "log" + "golang.org/x/net/context" + cloudflare "github.com/cloudflare/cloudflare-go" ) @@ -14,7 +16,7 @@ func ExampleAPI_ListZones_all() { } // Fetch all zones available to this user. - zones, err := api.ListZones() + zones, err := api.ListZones(context.TODO()) if err != nil { log.Fatal(err) } @@ -31,7 +33,7 @@ func ExampleAPI_ListZones_filter() { } // Fetch a slice of zones example.org and example.net. - zones, err := api.ListZones("example.org", "example.net") + zones, err := api.ListZones(context.TODO(), "example.org", "example.net") if err != nil { log.Fatal(err) } diff --git a/zone_test.go b/zone_test.go index b66f0e15d64..463ed063227 100644 --- a/zone_test.go +++ b/zone_test.go @@ -1,6 +1,7 @@ package cloudflare import ( + "context" "fmt" "net/http" "net/url" @@ -15,7 +16,7 @@ func TestZoneAnalyticsDashboard(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Equal(t, "2015-01-01T12:23:00Z", r.URL.Query().Get("since")) assert.Equal(t, "2015-01-02T12:23:00Z", r.URL.Query().Get("until")) assert.Equal(t, "true", r.URL.Query().Get("continuous")) @@ -321,7 +322,7 @@ func TestZoneAnalyticsDashboard(t *testing.T) { } continuous := true - d, err := client.ZoneAnalyticsDashboard("foo", ZoneAnalyticsOptions{ + d, err := client.ZoneAnalyticsDashboard(context.TODO(), "foo", ZoneAnalyticsOptions{ Since: &since, Until: &until, Continuous: &continuous, @@ -330,7 +331,7 @@ func TestZoneAnalyticsDashboard(t *testing.T) { assert.Equal(t, want, d) } - _, err = client.ZoneAnalyticsDashboard("bar", ZoneAnalyticsOptions{}) + _, err = client.ZoneAnalyticsDashboard(context.TODO(), "bar", ZoneAnalyticsOptions{}) assert.Error(t, err) } @@ -339,7 +340,7 @@ func TestZoneAnalyticsByColocation(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) assert.Equal(t, "2015-01-01T12:23:00Z", r.URL.Query().Get("since")) assert.Equal(t, "2015-01-02T12:23:00Z", r.URL.Query().Get("until")) assert.Equal(t, "true", r.URL.Query().Get("continuous")) @@ -571,7 +572,7 @@ func TestZoneAnalyticsByColocation(t *testing.T) { } continuous := true - d, err := client.ZoneAnalyticsByColocation("foo", ZoneAnalyticsOptions{ + d, err := client.ZoneAnalyticsByColocation(context.TODO(), "foo", ZoneAnalyticsOptions{ Since: &since, Until: &until, Continuous: &continuous, @@ -580,7 +581,7 @@ func TestZoneAnalyticsByColocation(t *testing.T) { assert.Equal(t, want, d) } - _, err = client.ZoneAnalyticsDashboard("bar", ZoneAnalyticsOptions{}) + _, err = client.ZoneAnalyticsDashboard(context.TODO(), "bar", ZoneAnalyticsOptions{}) assert.Error(t, err) } @@ -731,7 +732,7 @@ func TestCreateZoneFullSetup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -797,12 +798,7 @@ func TestCreateZoneFullSetup(t *testing.T) { mux.HandleFunc("/zones", handler) - actual, err := client.CreateZone( - "example.com", - false, - Account{ID: "01a7362d577a6c3019a474fd6f485823"}, - "full", - ) + actual, err := client.CreateZone(context.TODO(), "example.com", false, Account{ID: "01a7362d577a6c3019a474fd6f485823"}, "full") if assert.NoError(t, err) { assert.Equal(t, expectedFullZoneSetup, actual) @@ -814,7 +810,7 @@ func TestCreateZonePartialSetup(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, r.Method, "POST", "Expected method 'POST', got %s", r.Method) + assert.Equal(t, r.Method, http.MethodPost, "Expected method 'POST', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ "success": true, @@ -880,12 +876,7 @@ func TestCreateZonePartialSetup(t *testing.T) { mux.HandleFunc("/zones", handler) - actual, err := client.CreateZone( - "example.com", - false, - Account{ID: "01a7362d577a6c3019a474fd6f485823"}, - "partial", - ) + actual, err := client.CreateZone(context.TODO(), "example.com", false, Account{ID: "01a7362d577a6c3019a474fd6f485823"}, "partial") if assert.NoError(t, err) { assert.Equal(t, expectedPartialZoneSetup, actual) @@ -897,7 +888,7 @@ func TestFallbackOrigin_FallbackOrigin(t *testing.T) { defer teardown() mux.HandleFunc("/zones/foo/fallback_origin", func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") fmt.Fprintf(w, `{ @@ -912,7 +903,7 @@ func TestFallbackOrigin_FallbackOrigin(t *testing.T) { }`) }) - fallbackOrigin, err := client.FallbackOrigin("foo") + fallbackOrigin, err := client.FallbackOrigin(context.TODO(), "foo") want := FallbackOrigin{ ID: "fallback_origin", @@ -946,7 +937,7 @@ func TestFallbackOrigin_UpdateFallbackOrigin(t *testing.T) { }`) }) - response, err := client.UpdateFallbackOrigin("foo", FallbackOrigin{Value: "app.example.com"}) + response, err := client.UpdateFallbackOrigin(context.TODO(), "foo", FallbackOrigin{Value: "app.example.com"}) want := &FallbackOriginResponse{ Result: FallbackOrigin{ @@ -998,7 +989,7 @@ func TestZonePartialHasVerificationKey(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#zone-zone-details (plus an undocumented field verification_key from curl to API) @@ -1090,7 +1081,7 @@ func TestZonePartialHasVerificationKey(t *testing.T) { mux.HandleFunc("/zones/foo", handler) - z, err := client.ZoneDetails("foo") + z, err := client.ZoneDetails(context.TODO(), "foo") if assert.NoError(t, err) { assert.NotEmpty(t, z.VerificationKey) assert.Equal(t, z.VerificationKey, "foo-bar") @@ -1102,7 +1093,7 @@ func TestZoneDNSSECSetting(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method) + assert.Equal(t, http.MethodGet, r.Method, "Expected method 'GET', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#dnssec-properties @@ -1125,7 +1116,7 @@ func TestZoneDNSSECSetting(t *testing.T) { mux.HandleFunc("/zones/foo/dnssec", handler) - z, err := client.ZoneDNSSECSetting("foo") + z, err := client.ZoneDNSSECSetting(context.TODO(), "foo") if assert.NoError(t, err) { assert.Equal(t, z.Status, "active") assert.Equal(t, z.Flags, 257) @@ -1147,7 +1138,7 @@ func TestDeleteZoneDNSSEC(t *testing.T) { defer teardown() handler := func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "DELETE", r.Method, "Expected method 'DELETE', got %s", r.Method) + assert.Equal(t, http.MethodDelete, r.Method, "Expected method 'DELETE', got %s", r.Method) w.Header().Set("content-type", "application/json") // JSON data from: https://api.cloudflare.com/#dnssec-properties @@ -1158,7 +1149,7 @@ func TestDeleteZoneDNSSEC(t *testing.T) { mux.HandleFunc("/zones/foo/dnssec", handler) - z, err := client.DeleteZoneDNSSEC("foo") + z, err := client.DeleteZoneDNSSEC(context.TODO(), "foo") if assert.NoError(t, err) { assert.Equal(t, z, "foo") } @@ -1192,7 +1183,7 @@ func TestUpdateZoneDNSSEC(t *testing.T) { mux.HandleFunc("/zones/foo/dnssec", handler) - z, err := client.UpdateZoneDNSSEC("foo", ZoneDNSSECUpdateOptions{ + z, err := client.UpdateZoneDNSSEC(context.TODO(), "foo", ZoneDNSSECUpdateOptions{ Status: "active", }) if assert.NoError(t, err) {