api

package
v0.2.711 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package api is cfctl's shared HTTP layer for the Cloudflare API.

Every HTTP request cfctl makes — through the cloudflare-go SDK or the raw client in this package — goes through the http.Client built by NewHTTPClient. Its transport chain is:

readOnlyTransport → retryTransport → debugTransport → http.DefaultTransport

so the read-only guard is enforced in exactly one place, before anything is logged, retried, or sent. Retries (429/5xx) and per-attempt timeouts live in retryTransport, also shared by every client.

Index

Constants

View Source
const DefaultBaseURL = "https://api.cloudflare.com/client/v4"

DefaultBaseURL is the Cloudflare API v4 base.

View Source
const DefaultMaxPages = 1000

DefaultMaxPages bounds every pagination loop.

View Source
const GraphQLPath = "/client/v4/graphql"

GraphQLPath is the GraphQL Analytics endpoint path under the API base.

Variables

View Source
var (
	// MaxRetries is the number of retries after the first attempt.
	MaxRetries = 3
	// RetryBaseDelay doubles per retry (0.5s, 1s, 2s), capped at RetryMaxDelay.
	RetryBaseDelay = 500 * time.Millisecond
	RetryMaxDelay  = 8 * time.Second
	// MaxRetryAfter caps how long a Retry-After header can make us wait.
	MaxRetryAfter = 30 * time.Second
)

Retry policy. Variables so tests can shrink the delays.

View Source
var (

	// DebugOut is where --debug lines go (stderr; swapped in tests).
	DebugOut io.Writer = os.Stderr
	// Timeout bounds each HTTP request attempt (--timeout).
	Timeout = 30 * time.Second
)

Process-wide settings, set once from flags in the root command.

View Source
var ErrReadOnly = errors.New("read-only mode")

ErrReadOnly is wrapped by every error the read-only guard returns.

View Source
var MaxResponseBytes int64 = 512 << 20

MaxResponseBytes caps how much of a response body is read into memory.

View Source
var SpecPagination func(method, path string) *Pagination

SpecPagination, when set, returns the pagination parameters of the operation matching method and a concrete path (nil if unknown). cmd wires it to the embedded OpenAPI spec so that both `api request` and generated commands page correctly without per-command code.

Functions

func AllowedReadOnly

func AllowedReadOnly(method, path string) bool

AllowedReadOnly reports whether a request may be sent in read-only mode: GET, HEAD, OPTIONS, and POST to /client/v4/graphql (queries only by convention; Cloudflare's GraphQL API is analytics, read-only).

func BuildMultipart

func BuildMultipart(fields []FormField) ([]byte, string, error)

BuildMultipart encodes form fields as multipart/form-data and returns the body and its Content-Type (with boundary).

func Debug

func Debug() bool

Debug reports whether request logging is on.

func IsTimeout

func IsTimeout(err error) bool

IsTimeout reports whether err is a context deadline or network timeout.

func MatchTemplate

func MatchTemplate(templates []string, path string) int

MatchTemplate returns the index of the template best matching path (most literal segments), or -1. Exported for the spec wiring in cmd.

func Merge

func Merge(pages []json.RawMessage) (json.RawMessage, error)

Merge concatenates page results. Arrays are appended; objects have their array-valued fields appended (other fields come from the first page). A single page is returned unchanged.

func NewHTTPClient

func NewHTTPClient() *http.Client

NewHTTPClient returns the http.Client every cfctl API client must use. Each attempt is bounded by Timeout; whole commands (e.g. --all pagination) are not, so long runs aren't cut off.

func NewTransport

func NewTransport(next http.RoundTripper) http.RoundTripper

NewTransport wraps next (nil = http.DefaultTransport) in cfctl's read-only guard, retries, per-attempt timeout, and debug logging.

func ReadData

func ReadData(spec string, stdin io.Reader) ([]byte, error)

ReadData resolves a --data value: "@file" reads a file, "-" reads stdin, anything else is used literally.

func ReadOnly

func ReadOnly() bool

ReadOnly reports whether the read-only guard is on, via --read-only or CFCTL_READONLY (any value except "", "0", "false", "no", "off").

func SetDebug

func SetDebug(on bool)

SetDebug turns request logging on or off (the --debug flag).

func SetReadOnly

func SetReadOnly(on bool)

SetReadOnly turns the read-only guard on or off (the --read-only flag).

Types

type Client

type Client struct {
	// BaseURL is the API base, e.g. https://api.cloudflare.com/client/v4.
	BaseURL string

	HTTP *http.Client
	// contains filtered or unexported fields
}

Client is a raw Cloudflare API v4 client. It knows auth, the response envelope, and pagination; it knows nothing about individual endpoints.

func New

func New(token, baseURL string) *Client

New returns a raw client using the shared transport (read-only guard, retries, timeouts, debug logging). baseURL "" means DefaultBaseURL.

func (*Client) All

func (c *Client) All(ctx context.Context, r Request, maxPages int) (*PageResult, error)

All fetches every page of a list endpoint and concatenates the results.

Which query parameters page the endpoint comes from r.Paging, else SpecPagination (the OpenAPI spec), else the response itself. Each response is then checked in this order:

  • cursor: a next token in result_info, the result, or the body (cursor, cursors.after, next_cursor, nextCursor, next_page_token, continuation_token, nextContinuationToken, ...) → repeat with the endpoint's token parameter (cursor, page_token, continuation_token, continuationToken, next_cursor, scan_cursor). An explicit has_more/is_truncated=false stops.
  • page: page or page_no → next page while total_pages, total_count, has_more, or a full page (count ≥ per_page/page_size/pageSize/perPage) says there is more.
  • offset: offset/limit → offset += items while total or a full page says there is more.
  • before: newest-first time windows (Stream) → before = the last item's created time while the page is full.
  • anything else → the single response is returned.

The loop stops after maxPages requests (≤0 means DefaultMaxPages), on an empty page, a repeated cursor, or a page identical to the previous one (an endpoint ignoring the page parameter), so it always terminates.

func (*Client) Do

func (c *Client) Do(ctx context.Context, r Request) (*Response, error)

Do sends a request and decodes the envelope. Non-2xx statuses and success=false envelopes return *Error (with the Response attached).

func (*Client) GraphQL

func (c *Client) GraphQL(ctx context.Context, query string, variables map[string]any) ([]byte, error)

GraphQL posts a query to the GraphQL Analytics API and returns the raw response body ({"data":...,"errors":...}). GraphQL-level errors are not turned into Go errors here; HTTP errors are.

func (*Client) URL

func (c *Client) URL(path string, q url.Values) (string, error)

URL builds the full URL for a request path and query.

type Envelope

type Envelope struct {
	Success    *bool           `json:"success"`
	Errors     []Message       `json:"errors"`
	Messages   []Message       `json:"messages"`
	Result     json.RawMessage `json:"result"`
	ResultInfo *ResultInfo     `json:"result_info,omitempty"`
}

Envelope is Cloudflare's standard response wrapper.

type Error

type Error struct {
	Status       int
	Method, Path string
	Errors       []Message
	// Response is the failed response (for --raw output).
	Response *Response
}

Error is a non-2xx response or an envelope with success=false. It never includes request headers, so the token can't leak through it.

func (*Error) Error

func (e *Error) Error() string

type FormField

type FormField struct {
	Name        string
	Value       string // literal value (when File == "")
	File        string // path to upload
	FileName    string
	ContentType string
}

FormField is one --form k=v or k=@file[;type=mime][;filename=name] value.

func ParseFormField

func ParseFormField(s string) (FormField, error)

ParseFormField parses curl-style form syntax:

name=value
name=@path/to/file
name=@path/to/file;type=application/javascript+module
name=@path;filename=worker.js;type=text/javascript

A literal value may carry ";type=..." too (e.g. metadata=...;type=application/json).

type Message

type Message struct {
	Code    int    `json:"code,omitempty"`
	Message string `json:"message"`
}

Message is one entry in an envelope's errors or messages.

type PageResult

type PageResult struct {
	// Result is the concatenation of every page's result (see Merge).
	Result json.RawMessage
	// Pages is the number of requests made.
	Pages int
	// Truncated is true when maxPages stopped the loop early.
	Truncated bool
	// Last is the last page's response.
	Last *Response
	// Style is the pagination style that was followed: "cursor", "page",
	// "offset", "before", or "" for a single page.
	Style string
}

PageResult is the outcome of All.

type Pagination

type Pagination struct {
	// PageParam is the page-number parameter: "page" or "page_no".
	PageParam string
	// SizeParam is the page-size parameter: per_page, page_size, pageSize,
	// perPage, or limit.
	SizeParam string
	// CursorParam is the opaque-token parameter: cursor, page_token,
	// continuation_token, continuationToken, next_cursor, or scan_cursor.
	CursorParam string
	// OffsetParam / LimitParam are offset/limit pagination ("offset", "limit").
	OffsetParam, LimitParam string
	// BeforeParam is a time-window parameter ("before") that pages backwards
	// through newest-first lists by the last item's creation time (Stream).
	BeforeParam string
}

Pagination names the query parameters an endpoint pages with. Empty fields mean the endpoint doesn't take that parameter. A nil Request.Paging means "look the endpoint up in the API spec" (see SpecPagination), falling back to response-driven detection.

func PaginationFromParams

func PaginationFromParams(names []string) *Pagination

PaginationFromParams derives Pagination from an operation's query parameter names.

func (*Pagination) IsZero

func (p *Pagination) IsZero() bool

IsZero reports whether p names no parameters.

type ReadOnlyError

type ReadOnlyError struct {
	Method, Path string
}

ReadOnlyError is returned for a request refused by the read-only guard.

func (*ReadOnlyError) Error

func (e *ReadOnlyError) Error() string

func (*ReadOnlyError) Unwrap

func (e *ReadOnlyError) Unwrap() error

Unwrap lets errors.Is(err, ErrReadOnly) match.

type Request

type Request struct {
	Method      string
	Path        string
	Query       url.Values
	Header      http.Header
	Body        []byte
	ContentType string
	// Paging names the endpoint's pagination parameters for All; nil means
	// look them up in the API spec (SpecPagination) or detect them.
	Paging *Pagination
}

Request is one API call. Path is relative to BaseURL ("/zones") or an absolute URL on the same host.

type Response

type Response struct {
	Status      int
	Header      http.Header
	Body        []byte
	ContentType string
	// Envelope is set when the body is a Cloudflare JSON envelope.
	Envelope *Envelope
}

Response is a completed API call.

func (*Response) IsJSON

func (r *Response) IsJSON() bool

IsJSON reports whether the response body is JSON.

type ResultInfo

type ResultInfo struct {
	Page       float64 `json:"page,omitempty"`
	PerPage    float64 `json:"per_page,omitempty"`
	Count      float64 `json:"count,omitempty"`
	TotalCount float64 `json:"total_count,omitempty"`
	TotalPages float64 `json:"total_pages,omitempty"`
	Cursor     string  `json:"cursor,omitempty"`
	Cursors    *struct {
		After  string `json:"after,omitempty"`
		Before string `json:"before,omitempty"`
	} `json:"cursors,omitempty"`
}

ResultInfo is the envelope's pagination block. Cloudflare uses either page numbers (page, per_page, total_pages) or cursors (cursor, or cursors.after).

func (*ResultInfo) NextCursor

func (ri *ResultInfo) NextCursor() string

NextCursor returns the cursor for the next page, or "".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL