RepoCloudflare (Workers AI)Cloudflare (Workers AI)published Dec 3, 2015seen 5d

cloudflare/cloudflare-go

Go

Open original ↗

Captured source

source ↗
published Dec 3, 2015seen 5dcaptured 8hhttp 200method plain

cloudflare/cloudflare-go

Description: The official Go library for the Cloudflare API

Language: Go

License: Apache-2.0

Stars: 2016

Forks: 756

Open issues: 17

Created: 2015-12-03T15:21:49Z

Pushed: 2026-06-10T23:38:53Z

Default branch: main

Fork: no

Archived: no

README:

Cloudflare Go API Library

The Cloudflare Go library provides convenient access to the Cloudflare REST API from applications written in Go.

It is generated with Stainless.

MCP Server

Use the Cloudflare MCP Server to enable AI assistants to interact with this API, allowing them to explore endpoints, make test requests, and use documentation to help integrate this SDK into your application.

![Add to Cursor](https://cursor.com/en-US/install-mcp?name=cloudflare-mcp&config=eyJjb21tYW5kIjoibnB4IiwiYXJncyI6WyIteSIsImNsb3VkZmxhcmUtbWNwIl0sImVudiI6eyJDTE9VREZMQVJFX0FQSV9UT0tFTiI6IlNuM2xaSlRCWDZra2c3T2RjQlVBeE9POTYzR0VJeUdRcW5GVE9GWVkiLCJDTE9VREZMQVJFX0FQSV9LRVkiOiIxNDRjOWRlZmFjMDQ5NjljN2JmYWQ4ZWZhYThlYTE5NCIsIkNMT1VERkxBUkVfRU1BSUwiOiJ1c2VyQGV4YW1wbGUuY29tIiwiQ0xPVURGTEFSRV9BUElfVVNFUl9TRVJWSUNFX0tFWSI6InYxLjAtMTQ0YzlkZWZhYzA0OTY5YzdiZmFkOGVmLTYzMWE0MWQwMDNhMzJkMjVmZTg3ODA4MWVmMzY1YzQ5NTAzZjdmYWRhNjAwZGE5MzVlMjg1MWExYzczMjYwODRiODVjYmY2NDI5YzRiODU5ZGU4NDc1NzMxZGM5MmE5YzMyOTYzMWU2ZDU5ZTZjNzNkYTdiMTk4NDk3MTcyYjRjZWZlMDcxZDkwZDBmNWQyNzE5In19)

> Note: You may need to set environment variables in your MCP client.

Installation

import (
"github.com/cloudflare/cloudflare-go/v7" // imported as cloudflare
)

Or to pin the version:

go get -u 'github.com/cloudflare/cloudflare-go/v7@v7.5.0'

Requirements

This library requires Go 1.22+.

Usage

The full API of this library can be found in [api.md](api.md).

package main

import (
"context"
"fmt"

"github.com/cloudflare/cloudflare-go/v7"
"github.com/cloudflare/cloudflare-go/v7/option"
"github.com/cloudflare/cloudflare-go/v7/zones"
)

func main() {
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),
})
if err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", zone.ID)
}

Request fields

All request parameters are wrapped in a generic Field 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 sending null, false, '', or 0 on optional parameters. Any field not specified is not sent.

To construct fields with values, use the helpers String(), Int(), Float(), or most commonly, the generic F[T](). To send a null, use Null[T](), and to send a nonconforming value, use Raw[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
}),
}

Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field is null, not present, or invalid, the corresponding field will simply be its zero value.

All response structs also include a special JSON field, containing more detailed information about each property, which you can use like so:

if res.Name == "" {
// true if `"name"` is either not present or explicitly null
res.JSON.Name.IsNull()

// true if the `"name"` key was not present in the response JSON at all
res.JSON.Name.IsMissing()

// When the API returns data that cannot be coerced to the expected type:
if res.JSON.Name.IsInvalid() {
raw := res.JSON.Name.Raw()

legacyName := struct{
First string `json:"first"`
Last string `json:"last"`
}{}
json.Unmarshal([]byte(raw), &legacyName)
name = legacyName.First + " " + legacyName.Last
}
}

These .JSON structs also include an Extras map containing any properties in the json response that were not specified in the struct. This can be useful for API features not yet present in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()

RequestOptions

This library uses the functional options pattern. Functions defined in the option package return a RequestOption, which is a closure that mutates a RequestConfig. These options can be supplied to the client or at individual requests. For example:

client := cloudflare.NewClient(
// Adds a header to every request made by the client
option.WithHeader("X-Some-Header", "custom_header_info"),
)

client.Zones.New(context.TODO(), ...,
// Override the header
option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
// Add an undocumented field to the request body, using sjson syntax
option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
)

See the full list of request options.

Pagination

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.
for iter.Next() {
account := iter.Current()
fmt.Printf("%+v\n", account)
}
if err := iter.Err(); err != nil {
panic(err.Error())
}

Or you can use simple .List() methods to fetch a single page and receive a standard response object with additional helper methods like .GetNextPage(), e.g.:

page, err := client.Accounts.List(context.TODO(), accounts.AccountListParams{})
for page != nil {
for _, account := range page.Result {
fmt.Printf("%+v\n", account)
}
page, err = page.GetNextPage()
}
if err != nil {
panic(err.Error())
}

Errors

When the API returns a non-success status code, we return an error with type *cloudflare.Error. This contains the StatusCode, *http.Request, and…

Excerpt shown — open the source for the full document.