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

Overview

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.

Issues
  • 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

    opened by Sjeanpierre 23
  • 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

    opened by jacobbednarz 20
  • 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)
    }
    
    help wanted wontfix 
    opened by OJFord 15
  • 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.
    opened by favonia 14
  • 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.
    opened by favonia 14
  • [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.

    enhancement breaking 
    opened by elithrar 13
  • 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.

    workflow/pending-cloudflare 
    opened by Cyb3r-Jak3 12
  • 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.
    enhancement 
    opened by pims 12
  • 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"

    opened by mbrowne 12
  • [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.

    opened by Oldsouldier 12
  • 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.
    opened by sodabrew 11
  • Expose Blockpage.SuppressFooter field

    Expose Blockpage.SuppressFooter field

    Description

    Cloudflare documentation for TeamsAccount blockpage settings exposes suppress_footer field. https://api.cloudflare.com/#zero-trust-accounts-update-zero-trust-account-configuration

    Has your change been tested?

    Updated relevant test in teams_accounts.go.

    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.
    opened by NicholasAsimov 0
  • Add compatibility date and compatibility_flags to pages deployment configs

    Add compatibility date and compatibility_flags to pages deployment configs

    Description

    Adds compatibility date and compatibility flags to pages deployments Also fixes a couple cases where errors.New(fmt.Sprintf()) was being used instead of fmt.Errorf()

    Has your change been tested?

    Updated unit tests and they pass

    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.
    • [ ] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs. (soon)
    opened by Cyb3r-Jak3 3
  • Add support for listing R2 buckets

    Add support for listing R2 buckets

    Description

    Added the ability to list R2 buckets. A recent change (#1028) added support for creating and deleting R2 buckets but was missing the ability to list R2 buckets. This change adds support for listing R2 buckets.

    Has your change been tested?

    Enhanced r2_bucket_test.go with an additional test (TestR2_ListBuckets) to list R2 buckets. Also verified this against an active cloudflare account.

    Types of changes

    What sort of change does your code introduce/modify?

    • [X] New feature (non-breaking change which adds functionality)

    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.
    • [ ] This change is using publicly documented (api.cloudflare.com or developers.cloudflare.com) and stable APIs.

    Notes

    I could not find the repo for the api definition at api.cloudflare.com in order to update the documentation myself. I'm happy to do that if someone can give me a pointer to it. Also, how does this API path become a publicly documented and stable API? Thanks.

    workflow/pending-public-api 
    opened by rgcostea 6
  • Add some error type convenience functions for mocking and inspection

    Add some error type convenience functions for mocking and inspection

    Description

    Provide the ability to create the RequestError, etc types in other packages with the underlying Error type. Useful in our code for mocking these error types.

    Add the InternalErrorCodeIs to these errors as well to simplify checking the internal codes when working with these types.

    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.
    opened by jburnham 3
  • Remove double-unmarshalling

    Remove double-unmarshalling

    Description

    Fixes #1045

    Has your change been tested?

    Modified existing tests and ran go test.

    Screenshots (if appropriate):

    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.
    opened by vazexqi 5
  • Double-unmarshalling of `config` from cfd_tunnel/{{TUNNEL_ID}}/configurations is unnecessary

    Double-unmarshalling of `config` from cfd_tunnel/{{TUNNEL_ID}}/configurations is unnecessary

    Confirmation

    • [X] My issue isn't already found on the issue tracker.
    • [X] I have replicated my issue using the latest version of the library and it is still present.

    cloudflare-go version

    0.46.0

    Go environment

    Not relevant.

    Expected output

    I was expecting to use GetTunnelConfiguration and UpdateTunnelConfiguration. However, it seems like those methods are no longer compatible with the latest version of the API at https://api.cloudflare.com/#cloudflare-tunnel-configuration-properties

    I traced the error down to the double-marshaling that was done in https://github.com/cloudflare/cloudflare-go/pull/948#issuecomment-1166701661.

    Actual output

    Error unmarshalling.

    2022/08/16 12:38:25 Failed to get config for current tunnel: error unmarshalling the JSON response: json: cannot unmarshal object into Go struct field TunnelConfigurationStringifiedConfigResult.result.config of type string

    Code demonstrating the issue

    // Get the current configuration
    currentConfig, err := api.GetTunnelConfiguration(ctx, cloudflare.AccountIdentifier(accountId), tunnelId)
    if err != nil {
    	if _, ok := err.(*cloudflare.NotFoundError); ok {
    		shouldCreateFromScratch = true
    	} else {
    		log.Fatal("Failed to get config for current tunnel: ", err)
    	}
    }
    

    Steps to reproduce

    1. Create a sample go project that uses v0.46.0 of the API.
    2. Ensure that you have Cloudflare Tunnel with a Cloudflare Tunnel Configuration.
    3. Attempt to get/update the tunnel configuration
    4. Notice the serialization error

    References

    https://github.com/cloudflare/cloudflare-go/pull/948#issuecomment-1166701661

    opened by vazexqi 0
Releases(v0.47.1)
Owner
Cloudflare
Cloudflare
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

Ross Light 2 Feb 19, 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.

David Bond 107 Aug 12, 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

Jesse Szwedko 64 Jul 4, 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

Siva Prakash 3 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

Stratos Neiros 31 May 10, 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

null 16 May 13, 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

Bruno Souza 52 Jul 15, 2022
An API client for the Notion API implemented in Golang

An API client for the Notion API implemented in Golang

Anatoly Nosov 316 Aug 8, 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.

Amazon Web Services - Labs 686 Aug 16, 2022
A API scanner written in GOLANG to scan files recursively and look for API keys and IDs.

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

Sreekanth Sasi 3 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

Lucas TESSON 5 Jul 20, 2022
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

ytnobody / satoshi azuma 0 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

wolke.casa 1 Dec 21, 2021
Upcoming mobiles api (UpMob API)

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

null 0 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

Joshua Lawson 1 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

Abdul Salim 0 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

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

Triangula API server Minimalistic API server that calculates and serves artistic

Maik Schneider 0 Jan 10, 2022
Reservationbox-api - Reservationbox Api with golang

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

null 0 Jan 30, 2022