- Notifications
You must be signed in to change notification settings - Fork664
The official Go library for the Cloudflare API
License
cloudflare/cloudflare-go
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
The Cloudflare Go library provides convenient access to theCloudflare REST APIfrom applications written in Go.
It is generated withStainless.
import ("github.com/cloudflare/cloudflare-go/v4"// imported as cloudflare)
Or to pin the version:
go get -u'github.com/cloudflare/cloudflare-go/v4@v4.6.0'
This library requires Go 1.18+.
The full API of this library can be found inapi.md.
package mainimport ("context""fmt""github.com/cloudflare/cloudflare-go/v4""github.com/cloudflare/cloudflare-go/v4/option""github.com/cloudflare/cloudflare-go/v4/zones")funcmain() {client:=cloudflare.NewClient(option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"),// defaults to os.LookupEnv("CLOUDFLARE_API_TOKEN"))zone,err:=client.Zones.New(context.TODO(), zones.ZoneNewParams{Account:cloudflare.F(zones.ZoneNewParamsAccount{ID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),}),Name:cloudflare.F("example.com"),Type:cloudflare.F(zones.TypeFull),})iferr!=nil {panic(err.Error())}fmt.Printf("%+v\n",zone.ID)}
All request parameters are wrapped in a genericField
type,which we use to distinguish zero values from null or omitted fields.
This prevents accidentally sending a zero value if you forget a required parameter,and enables explicitly sendingnull
,false
,''
, or0
on optional parameters.Any field not specified is not sent.
To construct fields with values, use the helpersString()
,Int()
,Float()
, or most commonly, the genericF[T]()
.To send a null, useNull[T]()
, and to send a nonconforming value, useRaw[T](any)
. For example:
params:=FooParams{Name:cloudflare.F("hello"),// Explicitly send `"description": null`Description:cloudflare.Null[string](),Point:cloudflare.F(cloudflare.Point{X:cloudflare.Int(0),Y:cloudflare.Int(1),// In cases where the API specifies a given type,// but you want to send something else, use `Raw`:Z: cloudflare.Raw[int64](0.01),// sends a float}),}
All fields in response structs are value types (not pointers or wrappers).
If a given field isnull
, not present, or invalid, the corresponding fieldwill simply be its zero value.
All response structs also include a specialJSON
field, containing more detailedinformation about each property, which you can use like so:
ifres.Name=="" {// true if `"name"` is either not present or explicitly nullres.JSON.Name.IsNull()// true if the `"name"` key was not present in the response JSON at allres.JSON.Name.IsMissing()// When the API returns data that cannot be coerced to the expected type:ifres.JSON.Name.IsInvalid() {raw:=res.JSON.Name.Raw()legacyName:=struct{Firststring`json:"first"`Laststring`json:"last"`}{}json.Unmarshal([]byte(raw),&legacyName)name=legacyName.First+" "+legacyName.Last}}
These.JSON
structs also include anExtras
map containingany properties in the json response that were not specifiedin the struct. This can be useful for API features not yetpresent in the SDK.
body:=res.JSON.ExtraFields["my_unexpected_field"].Raw()
This library uses the functional options pattern. Functions defined in theoption
package return aRequestOption
, which is a closure that mutates aRequestConfig
. These options can be supplied to the client or at individualrequests. For example:
client:=cloudflare.NewClient(// Adds a header to every request made by the clientoption.WithHeader("X-Some-Header","custom_header_info"),)client.Zones.New(context.TODO(),...,// Override the headeroption.WithHeader("X-Some-Header","some_other_custom_header_info"),// Add an undocumented field to the request body, using sjson syntaxoption.WithJSONSet("some.json.path",map[string]string{"my":"object"}),)
See thefull list of request options.
This library provides some conveniences for working with paginated list endpoints.
You can use.ListAutoPaging()
methods to iterate through items across all pages:
iter:=client.Accounts.ListAutoPaging(context.TODO(), accounts.AccountListParams{})// Automatically fetches more pages as needed.foriter.Next() {account:=iter.Current()fmt.Printf("%+v\n",account)}iferr:=iter.Err();err!=nil {panic(err.Error())}
Or you can use simple.List()
methods to fetch a single page and receive a standard response objectwith additional helper methods like.GetNextPage()
, e.g.:
page,err:=client.Accounts.List(context.TODO(), accounts.AccountListParams{})forpage!=nil {for_,account:=rangepage.Result {fmt.Printf("%+v\n",account)}page,err=page.GetNextPage()}iferr!=nil {panic(err.Error())}
When the API returns a non-success status code, we return an error with type*cloudflare.Error
. This contains theStatusCode
,*http.Request
, and*http.Response
values of the request, as well as the JSON of the error body(much like other response objects in the SDK).
To handle errors, we recommend that you use theerrors.As
pattern:
_,err:=client.Zones.Get(context.TODO(), zones.ZoneGetParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),})iferr!=nil {varapierr*cloudflare.Erroriferrors.As(err,&apierr) {println(string(apierr.DumpRequest(true)))// Prints the serialized HTTP requestprintln(string(apierr.DumpResponse(true)))// Prints the serialized HTTP response}panic(err.Error())// GET "/zones/{zone_id}": 400 Bad Request { ... }}
When other errors occur, they are returned unwrapped; for example,if HTTP transport fails, you might receive*url.Error
wrapping*net.OpError
.
Requests do not time out by default; use context to configure a timeout for a request lifecycle.
Note that if a request isretried, the context timeout does not start over.To set a per-retry timeout, useoption.WithRequestTimeout()
.
// This sets the timeout for the request, including all the retries.ctx,cancel:=context.WithTimeout(context.Background(),5*time.Minute)defercancel()client.Zones.Edit(ctx,zones.ZoneEditParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),},// This sets the per-retry timeoutoption.WithRequestTimeout(20*time.Second),)
Request parameters that correspond to file uploads in multipart requests are typed asparam.Field[io.Reader]
. The contents of theio.Reader
will by default be sent as a multipart formpart with the file name of "anonymous_file" and content-type of "application/octet-stream".
The file name and content-type can be customized by implementingName() string
orContentType() string
on the run-time type ofio.Reader
. Note thatos.File
implementsName() string
, so afile returned byos.Open
will be sent with the file name on disk.
We also provide a helpercloudflare.FileParam(reader io.Reader, filename string, contentType string)
which can be used to wrap anyio.Reader
with the appropriate file name and content type.
// A file from the file systemfile,err:=os.Open("/path/to/file")api_gateway.UserSchemaNewParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File: cloudflare.F[io.Reader](file),Kind:cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}// A file from a stringapi_gateway.UserSchemaNewParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File: cloudflare.F[io.Reader](strings.NewReader("my file contents")),Kind:cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}// With a custom filename and contentTypeapi_gateway.UserSchemaNewParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File:cloudflare.FileParam(strings.NewReader(`{"hello": "foo"}`),"file.go","application/json"),Kind:cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}
Certain errors will be automatically retried 2 times by default, with a short exponential backoff.We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,and >=500 Internal errors.
You can use theWithMaxRetries
option to configure or disable this:
// Configure the default for all requests:client:=cloudflare.NewClient(option.WithMaxRetries(0),// default is 2)// Override per-request:client.Zones.Get(context.TODO(),zones.ZoneGetParams{ZoneID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),},option.WithMaxRetries(5),)
You can access the raw HTTP response data by using theoption.WithResponseInto()
request option. This is useful whenyou need to examine response headers, status codes, or other details.
// Create a variable to store the HTTP responsevarresponse*http.Responsezone,err:=client.Zones.New(context.TODO(),zones.ZoneNewParams{Account:cloudflare.F(zones.ZoneNewParamsAccount{ID:cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),}),Name:cloudflare.F("example.com"),Type:cloudflare.F(zones.TypeFull),},option.WithResponseInto(&response),)iferr!=nil {// handle error}fmt.Printf("%+v\n",zone)fmt.Printf("Status Code: %d\n",response.StatusCode)fmt.Printf("Headers: %+#v\n",response.Header)
This library is typed for convenient access to the documented API. If you need to access undocumentedendpoints, params, or response properties, the library can still be used.
To make requests to undocumented endpoints, you can useclient.Get
,client.Post
, and other HTTP verbs.RequestOptions
on the client, such as retries, will be respected when making these requests.
var (// params can be an io.Reader, a []byte, an encoding/json serializable object,// or a "…Params" struct defined in this library.paramsmap[string]interface{}// result can be an []byte, *http.Response, a encoding/json deserializable object,// or a model defined in this library.result*http.Response)err:=client.Post(context.Background(),"/unspecified",params,&result)iferr!=nil { …}
To make requests using undocumented parameters, you may use either theoption.WithQuerySet()
or theoption.WithJSONSet()
methods.
params:=FooNewParams{ID:cloudflare.F("id_xxxx"),Data:cloudflare.F(FooNewParamsData{FirstName:cloudflare.F("John"), }),}client.Foo.New(context.Background(),params,option.WithJSONSet("data.last_name","Doe"))
To access undocumented response properties, you may either access the raw JSON of the response as a stringwithresult.JSON.RawJSON()
, or get the raw JSON of a particular field on the result withresult.JSON.Foo.Raw()
.
Any fields that are not present on the response struct will be saved and can be accessed byresult.JSON.ExtraFields()
which returns the extra fields as amap[string]Field
.
We provideoption.WithMiddleware
which applies the givenmiddleware to requests.
funcLogger(req*http.Request,next option.MiddlewareNext) (res*http.Response,errerror) {// Before the requeststart:=time.Now()LogReq(req)// Forward the request to the next handlerres,err=next(req)// Handle stuff after the requestend:=time.Now()LogRes(res,err,start-end)returnres,err}client:=cloudflare.NewClient(option.WithMiddleware(Logger),)
When multiple middlewares are provided as variadic arguments, the middlewaresare applied left to right. Ifoption.WithMiddleware
is givenmultiple times, for example first in the client then the method, themiddleware in the client will run first and the middleware given in the methodwill run next.
You may also replace the defaulthttp.Client
withoption.WithHTTPClient(client)
. Only one http client isaccepted (this overwrites any previous client) and receives requests after anymiddleware has been applied.
This package generally followsSemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
- Changes to library internals which are technically public but not intended or documented for external use.(Please open a GitHub issue to let us know if you are relying on such internals.)
- Changes that we do not expect to impact the vast majority of users in practice.
This SDK is actively maintained, however, many issues are tracked outside of GitHub on internal Cloudflare systems. Members of the community are welcome to join and discuss your issues during our twice monthly triage meetings. For urgent issues, please contactCloudflare support.
About
The official Go library for the Cloudflare API
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.