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
- Variables
- func AllowedReadOnly(method, path string) bool
- func BuildMultipart(fields []FormField) ([]byte, string, error)
- func Debug() bool
- func IsTimeout(err error) bool
- func MatchTemplate(templates []string, path string) int
- func Merge(pages []json.RawMessage) (json.RawMessage, error)
- func NewHTTPClient() *http.Client
- func NewTransport(next http.RoundTripper) http.RoundTripper
- func ReadData(spec string, stdin io.Reader) ([]byte, error)
- func ReadOnly() bool
- func SetDebug(on bool)
- func SetReadOnly(on bool)
- type Client
- func (c *Client) All(ctx context.Context, r Request, maxPages int) (*PageResult, error)
- func (c *Client) Do(ctx context.Context, r Request) (*Response, error)
- func (c *Client) GraphQL(ctx context.Context, query string, variables map[string]any) ([]byte, error)
- func (c *Client) URL(path string, q url.Values) (string, error)
- type Envelope
- type Error
- type FormField
- type Message
- type PageResult
- type Pagination
- type ReadOnlyError
- type Request
- type Response
- type ResultInfo
Constants ¶
const DefaultBaseURL = "https://api.cloudflare.com/client/v4"
DefaultBaseURL is the Cloudflare API v4 base.
const DefaultMaxPages = 1000
DefaultMaxPages bounds every pagination loop.
const GraphQLPath = "/client/v4/graphql"
GraphQLPath is the GraphQL Analytics endpoint path under the API base.
Variables ¶
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.
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.
var ErrReadOnly = errors.New("read-only mode")
ErrReadOnly is wrapped by every error the read-only guard returns.
var MaxResponseBytes int64 = 512 << 20
MaxResponseBytes caps how much of a response body is read into memory.
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 ¶
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 ¶
BuildMultipart encodes form fields as multipart/form-data and returns the body and its Content-Type (with boundary).
func MatchTemplate ¶
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 ¶
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 ¶
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 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 ¶
New returns a raw client using the shared transport (read-only guard, retries, timeouts, debug logging). baseURL "" means DefaultBaseURL.
func (*Client) All ¶
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 ¶
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.
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.
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 ¶
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 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.
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 "".