Documentation
¶
Overview ¶
Package r2 holds cfctl's R2 helpers that don't depend on Cobra: object listing over the REST API, operation classes and pricing, cost estimates, size formatting, and the S3-compatible client used for multipart uploads and sync.
Index ¶
- Constants
- Variables
- func BucketPath(acct, bucket string, segs ...string) string
- func DeleteKeys(ctx context.Context, c *s3.Client, bucket string, keys []string) ([]string, error)
- func DownloadFile(ctx context.Context, c *s3.Client, bucket, key, path string) (int64, error)
- func Excluded(rel string, globs []string) bool
- func Ext(key string) string
- func FileMD5(p string) (string, error)
- func HumanBytes(n float64) string
- func HumanCount(n float64) string
- func IsNotFound(err error) bool
- func IsReadOnly(err error) bool
- func JurisdictionHeader(j string) http.Header
- func NewS3(acct, jurisdiction string, creds TempCredentials) *s3.Client
- func ObjectPath(acct, bucket, key string) string
- func OpClass(action string) string
- func PrefixAt(key, base string, depth int) string
- func RESTStorageClass(c string) string
- func S3Endpoint(acct, jurisdiction string) string
- func S3StorageClass(c string) string
- func SortedKeys[V any](m map[string]V) []string
- func UploadFile(ctx context.Context, c *s3.Client, bucket, key, path string, o PutOptions, ...) error
- func WriteFileAtomic(path string, r io.Reader) (int64, error)
- type Cost
- type ListOptions
- type ListResult
- type LocalFile
- type MultipartOptions
- type Object
- type Price
- type PutOptions
- type SyncItem
- type SyncPlan
- type TempCredentials
- type Usage
Constants ¶
const ( Standard = "Standard" InfrequentAccess = "InfrequentAccess" )
Storage classes as R2 names them.
const ( ClassA = "A" ClassB = "B" ClassFree = "free" )
Operation classes.
const DefaultPartSize int64 = 16 << 20
DefaultPartSize is 16 MiB.
const GB = 1e9
GB is a decimal gigabyte, the unit R2 bills in.
const MinPartSize int64 = 5 << 20
MinPartSize is S3's minimum for every part but the last.
const PricingSource = "developers.cloudflare.com/r2/pricing, checked 2026-10-03"
PricingSource is shown next to cost estimates.
const S3EndpointEnv = "CFCTL_R2_S3_ENDPOINT"
S3EndpointEnv overrides the S3 endpoint (tests, or a custom gateway).
Variables ¶
var Prices = map[string]Price{ Standard: { StorageGBMonth: 0.015, ClassAPerMillion: 4.50, ClassBPerMillion: 0.36, FreeStorageGB: 10, FreeClassA: 1_000_000, FreeClassB: 10_000_000, }, InfrequentAccess: { StorageGBMonth: 0.01, ClassAPerMillion: 9.00, ClassBPerMillion: 0.90, RetrievalPerGB: 0.01, }, }
Prices is the R2 price table.
source: developers.cloudflare.com/r2/pricing, checked 2026-10-03. Egress is free. Billable units are rounded up (partial GB-months and partial millions of requests bill as a whole unit). DeleteObject, DeleteBucket and AbortMultipartUpload are free. The free tier applies to Standard storage only; Infrequent Access has none.
Functions ¶
func BucketPath ¶
BucketPath is /accounts/{acct}/r2/buckets/{bucket} plus optional suffix segments (each path-escaped).
func DeleteKeys ¶
DeleteKeys deletes keys with S3 DeleteObjects (1000 per request) and returns the keys that failed.
func DownloadFile ¶
DownloadFile writes bucket/key to path (via a temp file, renamed into place).
func Excluded ¶
Excluded reports whether rel matches any glob (matched against the full relative path and against the base name).
func HumanBytes ¶
HumanBytes formats a byte count with decimal units (R2 bills in GB).
func HumanCount ¶
HumanCount formats a count with thousands separators.
func IsReadOnly ¶
IsReadOnly reports whether err (possibly wrapped by the AWS SDK) is the read-only guard's refusal.
func JurisdictionHeader ¶
JurisdictionHeader returns the cf-r2-jurisdiction header for j, or nil.
func NewS3 ¶
func NewS3(acct, jurisdiction string, creds TempCredentials) *s3.Client
NewS3 builds an S3 client for R2. It uses cfctl's shared HTTP client, so the read-only guard (only GET/HEAD/OPTIONS go out) and --debug logging apply.
func ObjectPath ¶
ObjectPath is the REST path of one object. The key is escaped as a single segment (slashes become %2F), as the API expects.
func OpClass ¶
OpClass returns ClassA, ClassB, or ClassFree for an R2 action type (GraphQL r2OperationsAdaptiveGroups dimensions.actionType).
Class A: PutObject, CopyObject, multipart (create/upload part/complete, list uploads/parts), List*, PutBucket*, LifecycleStorageTierTransition. Free: DeleteObject, DeleteBucket, AbortMultipartUpload. Everything else (GetObject, HeadObject, HeadBucket, Get*, ...) is Class B.
func PrefixAt ¶
PrefixAt groups key by the first `depth` path segments below base ("a/b/" for key "base/a/b/c.png", depth 2). Objects with fewer directory levels group under their own directory plus " (files)"; objects directly under base group as "(files)".
func RESTStorageClass ¶
RESTStorageClass maps a storage class to the REST API's name (the cf-r2-storage-class header and bucket storageClass): Standard or InfrequentAccess.
func S3Endpoint ¶
S3Endpoint returns the account's R2 S3 endpoint for a jurisdiction.
func S3StorageClass ¶
S3StorageClass maps a storage class to the S3 API's name: R2's S3 API takes x-amz-storage-class STANDARD or STANDARD_IA, while the REST API (cf-r2-storage-class) takes Standard or InfrequentAccess.
func SortedKeys ¶
SortedKeys returns a map's keys sorted.
func UploadFile ¶
func UploadFile(ctx context.Context, c *s3.Client, bucket, key, path string, o PutOptions, mo MultipartOptions) error
UploadFile uploads a local file to bucket/key: one PutObject for files up to the part size, a multipart upload above it. A failed multipart upload is aborted.
Types ¶
type Cost ¶
type Cost struct {
Storage, ClassA, ClassB, Retrieval, Total float64
}
Cost is a cost estimate for one storage class.
type ListOptions ¶
type ListOptions struct {
Prefix string
Delimiter string // "/" for a folder view; "" lists recursively
PerPage int // ≤0 → 1000 (the maximum)
// Limit stops after this many objects (≤0 → no limit).
Limit int
// MaxPages bounds the loop (≤0 → api.DefaultMaxPages).
MaxPages int
// Jurisdiction sets cf-r2-jurisdiction ("" or "default" → none).
Jurisdiction string
}
ListOptions selects objects to list.
type ListResult ¶
type ListResult struct {
Objects []Object `json:"objects"`
// Prefixes are the common prefixes ("folders") when Delimiter is set.
Prefixes []string `json:"prefixes,omitempty"`
Pages int `json:"-"`
Truncated bool `json:"truncated,omitempty"`
}
ListResult is the outcome of List.
func List ¶
func List(ctx context.Context, c *api.Client, acct, bucket string, o ListOptions, fn func(page []Object)) (*ListResult, error)
List lists objects through the REST API, following the cursor until the listing isn't truncated. fn, if set, is called with each page's objects (useful for progress); the objects are also accumulated unless fn returns false for "don't keep".
type LocalFile ¶
type LocalFile struct {
Rel string // slash-separated path relative to the root
Path string // OS path
Size int64
}
LocalFile is one file under a sync source directory.
type MultipartOptions ¶
type MultipartOptions struct {
PartSize int64 // bytes; ≥5 MiB
Concurrency int
// Progress is called after each part with the bytes uploaded so far.
Progress func(done int64)
}
MultipartOptions tune multipart uploads.
type Object ¶
type Object struct {
Key string `json:"key"`
ETag string `json:"etag,omitempty"`
LastModified string `json:"last_modified,omitempty"`
Size int64 `json:"size"`
HTTPMetadata map[string]any `json:"http_metadata,omitempty"`
CustomMetadata map[string]string `json:"custom_metadata,omitempty"`
StorageClass string `json:"storage_class,omitempty"`
}
Object is one R2 object as the REST API lists it.
func Stat ¶
func Stat(ctx context.Context, c *api.Client, acct, bucket, key, jurisdiction string) (*Object, error)
Stat returns one object's listing entry (size, etag, metadata), or (nil, nil) if no object has exactly that key. The REST API has no HEAD; listing with prefix=key returns the key itself first when it exists.
type Price ¶
type Price struct {
// StorageGBMonth is USD per GB-month of stored data.
StorageGBMonth float64
// ClassAPerMillion / ClassBPerMillion are USD per million requests.
ClassAPerMillion float64
ClassBPerMillion float64
// RetrievalPerGB is USD per GB read back (Infrequent Access only).
RetrievalPerGB float64
// Free tier (per account per month; Standard only).
FreeStorageGB float64
FreeClassA float64
FreeClassB float64
}
Price is one storage class's price list.
type PutOptions ¶
type PutOptions struct {
ContentType string
CacheControl string
ContentDisposition string
ContentEncoding string
ContentLanguage string
StorageClass string
Metadata map[string]string
}
PutOptions are the object metadata for an upload.
type SyncItem ¶
type SyncItem struct {
Key string `json:"key"`
Path string `json:"path"`
Size int64 `json:"size"`
Reason string `json:"reason"` // "new" or "changed"
}
SyncItem is one transfer in a sync plan.
type SyncPlan ¶
type SyncPlan struct {
Transfers []SyncItem `json:"transfers"`
// Deletes are remote keys (upload) or local paths (download) to remove.
Deletes []string `json:"deletes,omitempty"`
Unchanged int `json:"unchanged"`
Bytes int64 `json:"bytes"`
}
SyncPlan is what a sync would do.
type TempCredentials ¶
type TempCredentials struct {
AccessKeyID string `json:"accessKeyId"`
SecretAccessKey string `json:"secretAccessKey"`
SessionToken string `json:"sessionToken"`
}
TempCredentials are short-lived S3 credentials from POST /accounts/{id}/r2/temp-access-credentials.