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.

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

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

    opened by Cyb3r-Jak3 14
  • 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
  • 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
  • Upload multiple module workers

    Upload multiple module workers

    Current cloudflare-go version

    Latest

    Description

    It would be great to be able to upload ESM workers which have multiple modules (e.g. those with .wasm dependencies). As best as I can tell this is supported by the existing API using multipart form data (which is what wrangler is using to support this use case), so could be also be supported by cloudflare-go. I am happy to implement the feature/raise a PR but thought it might be good to discuss the design/whether this is something that would be accepted beforehand.

    Currently the interface for uploading a worker script is captured by the WorkerScriptParams type:

    // WorkerScriptParams provides a worker script and the associated bindings.
    type WorkerScriptParams struct {
    	Script string
    
    	// Module changes the Content-Type header to specify the script is an
    	// ES Module syntax script.
    	Module bool
    
    	// Bindings should be a map where the keys are the binding name, and the
    	// values are the binding content
    	Bindings map[string]WorkerBinding
    }
    

    At present the Script field of this struct is the only way to pass module code to be uploaded. I can think of a few options to extend this to support multiple-module use cases:

    • Change Script to Scripts, allowing requests to take multiple scripts. This would require us to add some validation to ensure that at least one script is passed, and likely some checks to prevent Module = true with multiple scripts. Scripts[0] would be the main worker script. A bit ugly, perhaps.
    • Add a new field, AdditionalScripts (better names welcome) that captures additional scripts, with Script becoming the main worker script. Again, we'd likely want to make sure that Module = true if this new field is not empty.
    • My particular use case is .wasm files. The CommonJS API already supports WASM bindings, but rejects them if Module = true. We could modify the code to move WASM bindings to the multi-part body if Module = true. This would not require us to change the function API, but could lead to unexpected behaviour/be a bad developer experience.

    We might need to tweak the Download* functions also, though I understand some work has gone into making these work with multipart workers already (though they may only be expecting a single part).

    Thoughts, critique and other feedback welcome on this -- it'd be great to bring cloudflare-go to parity with wrangler so that we can expose this functionality neatly in e.g. Terraform and Pulumi codebases.

    Use cases

    Supporting multi-module workers in cloudflare-go would lead to this support being available in Terraform/Pulumi, allowing infrastructure-as-code setups that don't depend on running wrangler commands.

    Potential cloudflare-go usage

    // WorkerScriptParams provides a worker script and the associated bindings.
    type WorkerScriptParams struct {
    	Script string
    
    	// Additional modules that should be uploaded as part of the script
    	AdditionalScripts string[]
    
    	// Module changes the Content-Type header to specify the script is an
    	// ES Module syntax script.
    	Module bool
    
    	// Bindings should be a map where the keys are the binding name, and the
    	// values are the binding content
    	Bindings map[string]WorkerBinding
    }
    

    References

    No response

    opened by lunaris 3
  • workers_kv: modernise all methods

    workers_kv: modernise all methods

    • Updates the methods to make the experimental client method signatures for consistency
    • Renames some methods to be clearer about what they do
    • Automatically paginate List* requests (except for keys due to potential load issues on larger result sets)

    Todo:

    • [x] Add changelog for all method renames/moves
    opened by jacobbednarz 2
  • Incomplete custom hostname (and custom hostname ssl) status constants

    Incomplete custom hostname (and custom hostname ssl) status constants

    Current cloudflare-go version

    v0.52.0

    Description

    custom_hostname.go has definitions for a subset of CustomHostnameStatus values (pending, active, moved, deleted, & blocked) but this is incomplete based on the API's custom hostname object definition. Missing values are: active_redeploying, pending_deletion, pending_blocked, pending_migration, pending_provisioned, test_pending, test_active, test_active_apex, test_blocked, test_failed, provisioned

    Additionally, there are no constants for the CustomHostnameSSL.Status which is defined as a string. Valid values per the API doc are initializing, pending_validation, deleted, pending_issuance, pending_deployment, pending_deletion, pending_expiration, expired, active, initializing_timed_out, validation_timed_out, issuance_timed_out, deployment_timed_out, deletion_timed_out, pending_cleanup, staging_deployment, staging_active, deactivating, inactive, backup_issued, holding_deployment

    Use cases

    A user of cloudflare-go would like to the status value in a custom hostname object (and custom hostname SSL object) using the constants defined in the go library without adding hard-coded strings to their code.

    Potential cloudflare-go usage

    switch currentRecord.Status {
    	case cloudflare.MOVED, cloudflare.DELETED:
    		// do things
    	// !! ACTIVE_REDEPLOYING is not defined today
    	case cloudflare.ACTIVE, cloudflare.ACTIVE_REDEPLOYING, cloudflare.PENDING:
    		// do things
    	case cloudflare.BLOCKED:
    		// do things
    

    References

    No response

    opened by rcj4747 0
  • Add support of duration field to CreateAccessServiceToken

    Add support of duration field to CreateAccessServiceToken

    Current cloudflare-go version

    latest

    Description

    Currently it is impossible to set duration of created token, or update it duration. But it's possible to do that from Cloudflare Dashboard which seems to use same API methods.

    Use cases

    It could be very useful in cloudflare terraform provider, cause it would allow to create static long-lived access tokens.

    Potential cloudflare-go usage

    Nope
    

    References

    No response

    enhancement workflow/pending-public-api 
    opened by dm3ch 1
  • Update Tunnel API Structs

    Update Tunnel API Structs

    Update the Tunnel (cloudflared) API structs so that they reflect the current API/Cloudflared configs.

    Description

    Copied changes from cloudflared into this repo.

    Currently aswell not sure where to report but the docs (https://api.cloudflare.com/#cloudflare-tunnel-configuration-properties) State that the API returns a JSON string, however this is not the case.

    Has your change been tested?

    No.

    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)
    • [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.
    • [ ] 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.

    fixes #1098

    workflow/pending-public-api 
    opened by TroyKomodo 2
  • Update TunnelConfig Responses in documentation as well as in SDK

    Update TunnelConfig Responses in documentation as well as in SDK

    Current cloudflare-go version

    master

    Description

    The cloudflared instance for UnvalidatedIngressRule Can be seen here https://github.com/cloudflare/cloudflared/blob/6be36fa2c52634a2f4a3223f8f7cd1ac331102f9/config/configuration.go#L179

    This is the same type returned by the API response. However the SDK is missing the OriginRequest field.

    Use cases

    Parity with API & Cloudflared

    Potential cloudflare-go usage

    Parity with API & Cloudflared
    

    References

    No response

    opened by TroyKomodo 0
Releases(v0.54.0)
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 1 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.

David Bond 0 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

Jesse Szwedko 66 Nov 18, 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 33 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

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 55 Oct 6, 2022
An API client for the Notion API implemented in Golang

An API client for the Notion API implemented in Golang

Anatoly Nosov 343 Nov 9, 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 735 Nov 23, 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 Nov 2, 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