A Go library for interacting with Cloudflare's API v4.

cloudflare-go

Go Reference Test Go Report Card

Note: This library is under active development as we expand it to cover our (expanding!) API. Consider the public API of this package a little unstable as we work towards a v1.0.

A Go library for interacting with Cloudflare's API v4. This library allows you to:

  • Manage and automate changes to your DNS records within Cloudflare
  • Manage and automate changes to your zones (domains) on Cloudflare, including adding new zones to your account
  • List and modify the status of WAF (Web Application Firewall) rules for your zones
  • Fetch Cloudflare's IP ranges for automating your firewall whitelisting

A command-line client, flarectl, is also available as part of this project.

Features

The current feature list includes:

  • Cache purging
  • Cloudflare IPs
  • Custom hostnames
  • DNS Records
  • Firewall (partial)
  • Keyless SSL
  • Load Balancing
  • Logpush Jobs
  • Organization Administration
  • Origin CA
  • Railgun administration
  • Rate Limiting
  • User Administration (partial)
  • Virtual DNS Management
  • Web Application Firewall (WAF)
  • Zone Lockdown and User-Agent Block rules
  • Zones
  • Workers KV
  • Notifications
  • Gateway Locations

Pull Requests are welcome, but please open an issue (or comment in an existing issue) to discuss any non-trivial changes before submitting code.

Installation

You need a working Go environment.

go get github.com/cloudflare/cloudflare-go

Getting Started

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/cloudflare/cloudflare-go"
)

func main() {
	// Construct a new API object
	api, err := cloudflare.New(os.Getenv("CF_API_KEY"), os.Getenv("CF_API_EMAIL"))
	if err != nil {
		log.Fatal(err)
	}

	// Most API calls require a Context
	ctx := context.Background()

	// Fetch user details on the account
	u, err := api.UserDetails(ctx)
	if err != nil {
		log.Fatal(err)
	}
	// Print user details
	fmt.Println(u)

	// Fetch the zone ID
	id, err := api.ZoneIDByName("example.com") // Assuming example.com exists in your Cloudflare account already
	if err != nil {
		log.Fatal(err)
	}

	// Fetch zone details
	zone, err := api.ZoneDetails(ctx, id)
	if err != nil {
		log.Fatal(err)
	}
	// Print zone details
	fmt.Println(zone)
}

Also refer to the API documentation for how to use this package in-depth.

License

BSD licensed. See the LICENSE file for details.

Comments
  • Added support for Workers and Worker Routes

    Added support for Workers and Worker Routes

    Adds support for Cloudflare workers

    • https://developers.cloudflare.com/workers/api/
    • https://api.cloudflare.com/#worker-script-properties

    This does not yet support the enterprise routes[1] for workers as they are currently broken in the Cloudflare API

    [1] - https://developers.cloudflare.com/workers/api/config-api-for-enterprise/

    fixes #187

  • Add support for Spectrum Applications

    Add support for Spectrum Applications

    Implements support for managing Spectrum Applications via the API.

    API reference: https://developers.cloudflare.com/spectrum/api-reference/

    Fixes #207

  • Make CRUD API + pagination treatment consistent across resources [WIP]

    Make CRUD API + pagination treatment consistent across resources [WIP]

    This PR is a (breaking) change to the CreatePageRule signature, making it consistent with other Create~ functions:

    func (api *API) Create~(zoneID string, ~) (*~Response, error)
    

    Aside from motivations of consistency, without this API the user is unable to discover the server-created ID for the page rule without enumerating ListPageRule before and after creation - and assuming they are the only user at that instant.

    C.f. discussion in #108; ping @elithrar

    Example use: (Should I add a test? I can't seem to make existing *_test.go files fail, so I'm not clear if they're running when I do go test, or how to add one and be sure it's running.)

    package main
    
    import (
        "fmt"
        "os"
        cloudflare "github.com/cloudflare/cloudflare-go"
    )
    
    func main() {
        domain := os.Getenv("CLOUDFLARE_DOMAIN")
        api, err := cloudflare.New(os.Getenv("CLOUDFLARE_TOKEN"), os.Getenv("CLOUDFLARE_EMAIL"))
        if err != nil {
            fmt.Print(err)
            return
        }
    
        rule := cloudflare.PageRule{
            Targets: []cloudflare.PageRuleTarget{
                cloudflare.PageRuleTarget{
                    Target: "url",
                    Constraint: struct {
                         Operator string `json:"operator"`
                         Value    string `json:"value"`
                    }{
                         Operator: "matches",
                         Value:    fmt.Sprintf("test.%s", domain),
                    },
                },
            },
            Actions: []cloudflare.PageRuleAction{
                cloudflare.PageRuleAction{
                    ID:    "always_online",
                    Value: "on",
                },
            },
            Priority: 1,
            Status:   "active",
        }
    
        zoneID, err := api.ZoneIDByName(domain)
        if err != nil {
            fmt.Printf("Error finding zone %q: %s", domain, err)
            return
        }
    
        r, err := api.CreatePageRule(zoneID, rule)
        if err != nil {
            fmt.Printf("Failed to create page rule: %s", err)
            return nil
        }
    
        fmt.Printf("Result: %q", r.Result)
    }
    
  • Should fix the R2 bucket create endpoint

    Should fix the R2 bucket create endpoint

    Description

    Should fix the R2 bucket creation API request

    See https://github.com/cloudflare/wrangler2/pull/1653 Fixes #1033

    Has your change been tested?

    Unit tests pass

    Types of changes

    What sort of change does your code introduce/modify?

    • [X] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [X] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [X] I have added tests to cover my changes.
    • [X] All new and existing tests passed.
    • [X] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs.

    Should wait for wrangler to be merged to confirm that this is the correct fix.

  • feat(dns): normalize DNS record names

    feat(dns): normalize DNS record names

    This is a proof of concept of the proposed workaround in #688. We may or may not want this, depending on the discussion in #688. (I did not use the "Close" keyword because, in my opinion, a proper solution is to fix the API server instead of working around it.)

    Description

    See #688 and cloudflare/cloudflare-docs#1991. The current API server has trouble handling Unicode forms of IDNs.

    Has your change been tested?

    CreateDNSRecord, DNSRecords, and UpdateDNSRecord now call normalizeDomainName before accessing the API.

    Types of changes

    What sort of change does your code introduce/modify?

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [x] My change requires a change to the documentation.
    • [x] I have updated the documentation accordingly.
    • [x] I have added tests to cover my changes.
    • [x] All new and existing tests passed.
  • fix: multiple bugs in ListZones and ListZonesContext

    fix: multiple bugs in ListZones and ListZonesContext

    Description

    Current implementation of ListZonesContext has several issues (some shared by ListZones):

    1. Deadlock: if all workers failed, no one is receiving the error from the unbuffered errc.
    2. Deadlock: wg.Done() might not be called when there's an error, and wg.Wait() will block forever in that case.
    3. Racing: the built-in function append is not (obviously) thread-safe.
    4. Inefficiency: The first page is fetched twice.
    5. (Lack of) error-reporting: The errors from workers seem to be dropped.
    6. Code duplication: Code seems to be duplicated in ListZonesContext and ListZones.

    This PR draft attempts to fix all of the above by implementing a robust and correct ListZonesContext and calling ListZonesContext in ListZones when no zone names are specified.

    Has your change been tested?

    Yes. Two test cases were added to test concurrent fetching. Another two were added to test unexpected pagination options.

    Types of changes

    What sort of change does your code introduce/modify?

    • [x] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [x] I have added tests to cover my changes.
    • [x] All new and existing tests passed.
  • [breaking] New() returns error; supports Options.

    [breaking] New() returns error; supports Options.

    Ref: https://github.com/jamesog/cloudflare-go/issues/8

    • New now has a variadic opts argument that accepts a slice of Option.
    • Options for changing the underlying http.Client and http.Header map added.
    • Updated flarectl to handle the updated New() signature.
    • A new Error interface for returning different errors, and wrapping the cause, to provide easier inspection of errors without having to type-assert for all possible causes.

    The Error interface will be expanded to have a NetworkError implementation as well for wrapping HTTP errors, and possibly a (breaking) change to handle parsing/API response errors.

    We also now vendor deps for flarectl.

  • feat(workers): Adds support for Workers secrets

    feat(workers): Adds support for Workers secrets

    Description

    TODO Closes https://github.com/cloudflare/cloudflare-go/issues/474

    Has your change been tested?

    go test
    PASS
    ok  	github.com/cloudflare/cloudflare-go	0.218s
    

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [x] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [x] I have added tests to cover my changes.
    • [x] All new and existing tests passed.
  • Added Priority field to ZoneLockdown type

    Added Priority field to ZoneLockdown type

    Description

    This adds the Priority field for ZoneLockdown. It's currently undocumented but it seems to be already functional for both reading and writing.

    Has your change been tested?

    Yes, I ran the code in lockdown_example_test.go against a real Cloudflare account and it worked.

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [x] My change requires a change to the documentation.
    • [x] I have updated the documentation accordingly.
    • [x] I have added tests to cover my changes.
    • [x] All new and existing tests passed.

    Note: I am under the impression that the documentation is automatically generated in this case so that's why I marked yes for "I have updated the documentation accordingly"

  • [feat] ListZones internal pagination

    [feat] ListZones internal pagination

    Collect all available zones sequentially and return them to the user, rather than just the first page. The maximum page size is used to minimize API calls.

    This matches the DNSRecords implementation, and allows simple access to all zones until general pagination can be implemented.

  • Support for attaching a Worker to a Domain

    Support for attaching a Worker to a Domain

    Description

    Support for the new Custom Domain API at https://api.cloudflare.com/#worker-domain-attach-to-domain

    Has your change been tested?

    Works for me locally, unit tests will be added in PR review.

    Screenshots (if appropriate):

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [x] I have added tests to cover my changes.
    • [x] All new and existing tests passed.
    • [x] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com)
    • [ ] ... and stable APIs. unclear.
  • Allow for autopagination with custom page size

    Allow for autopagination with custom page size

    Signed-off-by: Artur Rodrigues [email protected]

    On https://github.com/cloudflare/cloudflare-go/pull/1151, ListDNSRecordsParams was introduced, which allows for users of the library to "search" for a specific page. What is not possible, however, is to have auto-pagination (i.e.: fetch all results) with a customer page size.

    This level of flexibility is interesting for those seeking to reduce the number of API calls made to Cloudflare if they're facing rate limits.

    Description

    On https://github.com/cloudflare/cloudflare-go/pull/1151, ListDNSRecordsParams was introduced, which embeds the ResultInfo struct.

    This bring the library to the same level of flexibility as the API itself. However, users opting for the auto-pagination feature are restricted to the default PerPage value of 50.

    If users decide to pass in a custom PerPage value, auto-pagination is silently turned off, with just the first page being returned.

    This PR simply changes the logic in ListDNSRecords to turn off autopaginate only if Page is passed in. With the current auto-pagination logic, a larger PerPage can be used with no side-effects. This seems sensible, as auto-pagination is an added feature of the library on top of the API.

    Imho, adding some documentation to the behaviour (current and new) is probably a good idea.

    Has your change been tested?

    Added new unit test for the pagination behaviour with a custom PerPage value. I've also validated it manually using flarectl.

    Screenshots (if appropriate):

    N/A

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [ ] New feature (non-breaking change which adds functionality)
    • [X] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [X] My code follows the code style of this project.
    • [X] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [X] I have added tests to cover my changes.
    • [X] All new and existing tests passed.
    • [X] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs.
  • fix!: allow clearing comments from the Go API

    fix!: allow clearing comments from the Go API

    Description

    Currently, empty DNS record comments will be understood as "unset" or "unspecified", making it impossible to clear the comment of an existing record. This PR fixes that. This is a breaking change, but since comments were introduced only in 0.58.0, chances are almost no applications depend on them yet. Technically, a new type DNSRecordComment was introduced to facilitate the correct marshaling of empty comments. See #1158 for further discussions of the current API behavior.

    The field Comment in DNSRecord and CreateDNSRecordParam is of type DNSRecordComment so that the zero value means "empty comment". However, the field comment in UpdateDNSRecordParam and ListDNSRecordsParam is of type *DNSRecordComment (notice the star) so that the zero value means "not filtering / not changing".

    One possible design choice is to make the field Comment of CreateDNSRecordParam of type *DNSRecordComment so that the zero value means "not specifying the comment", potentially matching the current behavior and also the design of Proxied field better (which is of type *bool instead of bool). I honestly do not know which one is better. Theoretically, we can and probably should change the type of the field Proxied in both DNSRecord and CreateDNSRecordParam to bool, but that will be out of the scope of this PR.

    Tagging @janik-cloudflare.

    This PR is incomplete. It still needs more test cases and entries for the Changelog.

    Has your change been tested?

    Barely, but it is tested at the same level of existing code about record comments. The official API documentation does not specify the expected behavior of the API for empty comments, either. I prefer waiting for people working at Cloudflare to add the test cases that they think are correct. I have manually tested the UpdateDNSRecord against the real Cloudflare server and it seemed to match what I expected.

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [x] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [x] My code follows the code style of this project.
    • [x] My change requires a change to the documentation.
    • [x] I have updated the documentation accordingly.
    • [ ] I have added tests to cover my changes.
    • [x] All new and existing tests passed.
    • [ ] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs.
  • Hide pagination info when auto-pagination is enabled

    Hide pagination info when auto-pagination is enabled

    Current cloudflare-go version

    0.54.0

    Description

    As mentioned in https://github.com/cloudflare/cloudflare-go/issues/612#issuecomment-890554597, I wonder if it makes sense for the functions with auto-pagination to return a modified ResultInfo saying that "there's only one big single page" (that is, Page is 1, TotalPages is 1, and Count matches Total, etc,).

    Use cases

    It should be an invariant that Count always matches the number of returned entries, hiding the details of pagination when auto-pagination is enabled.

    Potential cloudflare-go usage

    rs, ri, err := ListDNSRecords(ctx, ...)
    
    // len(rs) == ri.Count should be an invariant when err == nil
    

    References

    This was discussed in #612. The discussion there was dismissed because we intended to enable auto-pagination unconditionally back then. However, the new API allows library users to turn off auto-pagination and thus the same design question re-appears.

  • Complete removal of the global `api.AccountID`

    Complete removal of the global `api.AccountID`

    Current cloudflare-go version

    0.57

    Description

    Currently, only DNS firewall, Railgun, and ZoneIDByName can depend on the global api.AccountID (possibly via api.userBaseURL). I wonder if it is in the plan to completely stop using the global api.AccountID even outside the Terraform-related API. The current interface is slightly confusing because it is unclear when api.AccountID is used. If it is indeed planned to remove api.AccountID, I hope the field and the setter will soon be deprecated and then removed.

    Use cases

    A clear indication that api.AccountID will not be used (if that is the plan).

    Potential cloudflare-go usage

    // This does not address other endpoints related to Railgun
    type RailgunListOptions struct {
    	AccountID string
    	Direction string
    }
    
    // This does not address other endpoints related to DNS Firewall
    type DNSFirewallUserAnalyticsOptions struct {
    	AccountID string
    	Metrics   []string
    	Since     *time.Time
    	Until     *time.Time
    }
    

    References

    No response

  • GATE-3151: adds support for egress policies

    GATE-3151: adds support for egress policies

    Description

    Adds support for new Gateway Egress Policy rule type

    Types of changes

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [X] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)

    Checklist:

    • [X] My code follows the code style of this project.
    • [ ] My change requires a change to the documentation.
    • [ ] I have updated the documentation accordingly.
    • [ ] I have added tests to cover my changes.
    • [X] All new and existing tests passed.
    • [X] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs.
  • add delete for url normalization

    add delete for url normalization

    Description

    Adds delete function for url normalization that will disable the feature.

    What sort of change does your code introduce/modify?

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [x] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to change)
Go library for interacting with the Discord API (work-in-progress)

zombiezen Go Client for Discord zombiezen.com/go/discord is a WIP Go library for interacting with the Discord API. It differs from DiscordGo by provid

Nov 9, 2022
Terraform provider implementation for interacting with the Tailscale API.

Terraform Provider Tailscale This repository contains a Terraform provider implementation for interacting with the Tailscale API.

Oct 3, 2022
Go library for interacting with CircleCI

go-circleci Go library for interacting with CircleCI's API. Supports all current API endpoints allowing you do do things like: Query for recent builds

Nov 26, 2022
Simple-Weather-API - Simple weather api app created using golang and Open Weather API key
Simple-Weather-API - Simple weather api app created using golang and Open Weather API key

Simple Weather API Simple weather api app created using golang and Open Weather

Feb 6, 2022
Go library for accessing the MyAnimeList API: http://myanimelist.net/modules.php?go=api

go-myanimelist go-myanimelist is a Go client library for accessing the MyAnimeList API. Project Status The MyAnimeList API has been stable for years a

Sep 28, 2022
go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface

go-whatsapp-rest-API go-whatsapp-rest-API is a Go library for the WhatsApp web which use Swagger as api interface Multi-devices (MD) Support. This ver

Dec 15, 2022
Go client for the YNAB API. Unofficial. It covers 100% of the resources made available by the YNAB API.

YNAB API Go Library This is an UNOFFICIAL Go client for the YNAB API. It covers 100% of the resources made available by the YNAB API. Installation go

Oct 6, 2022
An API client for the Notion API implemented in Golang

An API client for the Notion API implemented in Golang

Dec 30, 2022
lambda-go-api-proxy makes it easy to port APIs written with Go frameworks such as Gin to AWS Lambda and Amazon API Gateway.

aws-lambda-go-api-proxy makes it easy to run Golang APIs written with frameworks such as Gin with AWS Lambda and Amazon API Gateway.

Jan 6, 2023
A API scanner written in GOLANG to scan files recursively and look for API keys and IDs.

GO FIND APIS _____ ____ ______ _____ _ _ _____ _____ _____ _____ / ____|/ __ \ | ____|_ _| \ | | __ \ /\ | __ \_

Oct 25, 2021
The NVD API is an unofficial Go wrapper around the NVD API.

NVD API The NVD API is an unofficial Go wrapper around the NVD API. Supports: CVE CPE How to use The following shows how to basically use the wrapper

Jan 7, 2023
A Wrapper Client for Google Spreadsheet API (Sheets API)

Senmai A Wrapper Client for Google Spreadsheet API (Sheets API) PREPARATION Service Account and Key File Create a service account on Google Cloud Plat

Nov 5, 2021
💾 Wolke API is the API behind Wolke image storage and processing aswell as user management

?? Wolke API Wolke API is the API behind Wolke image storage and processing aswell as user management Deploying To deploy Wolke Bot you'll need podman

Dec 21, 2021
Upcoming mobiles api (UpMob API)

upcoming_mobiles_api (UpMob API) UpMob API scraps 91mobiles.com to get devices i

Dec 21, 2021
Arweave-api - Arweave API implementation in golang

Arweave API Go implementation of the Arweave API Todo A list of endpoints that a

Jan 16, 2022
Api-product - A basic REST-ish API that allows you to perform CRUD operations for Products

Description A basic REST-ish API that allows you to perform CRUD operations for

Jan 3, 2022
Contact-api - API for websites I have designed that have to send unauthenticated email

contact https://aws.amazon.com/premiumsupport/knowledge-center/custom-headers-ap

Apr 11, 2022
Triangula-api-server - API server for processing images with Triangula

Triangula API server Minimalistic API server that calculates and serves artistic

Jan 10, 2022
Reservationbox-api - Reservationbox Api with golang
Reservationbox-api - Reservationbox Api with golang

reservationbox-api How to set up application Cloning git on this link : https://

Jan 30, 2022