Cloudflare Go Library

repository·main·Indexed 24 days ago

https://github.com/cloudflare/cloudflare-go

A type-safe Go wrapper for the Cloudflare REST API, automatically generated using Stainless. The library provides access to Cloudflare services such as Accounts, Zones, and Abuse Reports. It requires Go 1.22 or higher and features support for auto-paging, custom middleware, exponential backoff retries, and a generic Field type to distinguish between zero values and omitted fields.

Tokens
89.5K
Snippets
57
Records
878
Agent score
84%

What's inside cloudflare-go

  1. How request fields and zero values work

    main

    All request parameters are wrapped in a generic Field type. This allows the SDK to distinguish between a zero value (like 0, false, or "") and a field that was omitted or explicitly set to null.

    • Use cloudflare.F[T](value) to set a value.
    • Use cloudflare.Null[T]() to explicitly send a null value.
    • Use cloudflare.Raw[T](value) to send a value that doesn't strictly match the expected type (e.g., sending a float where an int is expected).
    • Helpers like String(), Int(), and Float() are also available.
    params := FooParams{
    	Name: cloudflare.F("hello"),
    
    	// Explicitly send `"description": null`
    	Description: cloudflare.Null[string](),
    
    	Point: cloudflare.F(cloudflare.Point{
    		X: cloudflare.Int(0),
    		Y: cloudflare.Int(1),
    
    		// In cases where the API specifies a given type,
    		// but you want to send something else, use `Raw`:
    		Z: cloudflare.Raw[int64](0.01), // sends a float
    	},
    }
  2. How response objects and the .JSON field work

    main

    Response struct fields are value types. If a field is null or missing in the API response, the struct field will contain its zero value.

    To inspect the actual state of the JSON response, use the .JSON field on the response object. This provides metadata about each property:

    • res.JSON.Field.IsNull(): True if the field was null or not present.
    • res.JSON.Field.IsMissing(): True if the key was not present in the JSON at all.
    • res.JSON.Field.IsInvalid(): True if the API returned data that couldn't be coerced to the expected type. Use res.JSON.Field.Raw() to get the raw data for manual unmarshaling.

    Additionally, .JSON.ExtraFields is a map containing any properties returned by the API that were not defined in the SDK's response struct.

    if res.Name == "" {
    	// true if `"name"` is either not present or explicitly null
    	res.JSON.Name.IsNull()
    
    	// true if the `"name"` key was not present in the response JSON at all
    	res.JSON.Name.IsMissing()
    
    	// When the API returns data that cannot be coerced to the expected type:
    	if res.JSON.Name.IsInvalid() {
    		raw := res.JSON.Name.Raw()
    
    		legacyName := struct{
    			First string ` + "`json:\"first\"`" + `
    			Last  string ` + "`json:\"last\"`" + `
    		}{}
    		json.Unmarshal([]byte(raw), &legacyName)
    		name = legacyName.First + " " + legacyName.Last
    	}
    }
    
    // Accessing undocumented fields
    body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
  3. Use shared parameter and response types

    main

    The cloudflare-go library uses a shared package to provide consistent types across different API services. These types are used for both request parameters and API responses to ensure uniformity in data structures like permissions, roles, and tokens.

    Shared Parameter Types:

    • shared.ASNParam
    • shared.CertificateCA
    • shared.CertificateRequestType
    • shared.PermissionGrantParam
    • shared.RatePlanParam
    • shared.RoleParam
    • shared.SortDirection
    • shared.SubscriptionParam
    • shared.TokenParam
    • shared.TokenConditionCIDRListParam
    • shared.TokenPolicyParam

    Shared Response Types:

    • shared.ASN
    • shared.AuditLog
    • shared.CertificateCA
    • shared.CertificateRequestType
    • shared.CloudflareTunnel
    • shared.ErrorData
    • shared.Member
    • shared.Permission
    • shared.PermissionGrant
    • shared.RatePlan
    • shared.ResponseInfo
    • shared.Role
    • shared.SortDirection
    • shared.Subscription
    • shared.Token
    • shared.TokenConditionCIDRList
    • shared.TokenPolicy
    • shared.TokenValue
  4. Configure requests using RequestOptions

    main

    The library uses the functional options pattern. RequestOption functions (from the option package) can be applied to the client (affecting all requests) or to individual method calls.

    Common options include:

    • option.WithHeader(key, value): Adds a header.
    • option.WithJSONSet(path, value): Adds an undocumented field to the request body using sjson syntax.
    • option.WithResponseInto(&http.Response): Captures the raw HTTP response.
    client := cloudflare.NewClient(
    	// Adds a header to every request made by the client
    	option.WithHeader("X-Some-Header", "custom_header_info"),
    )
    
    client.Zones.New(context.TODO(), ...,
    	// Override the header
    	option.WithHeader("X-Some-Header", "some_other_custom_header_info"),
    	// Add an undocumented field to the request body, using sjson syntax
    	option.WithJSONSet("some.json.path", map[string]string{"my": "object"}),
    )
  5. Migrate AI Search from v6 to v7

    main

    In v7.0.0, the SearchForAgents field and its associated types have been removed from all instance and namespace instance metadata structs. Code that attempts to read SearchForAgents from responses or set it in parameters will fail to compile.

    Actions Needed:

    1. Remove all references to SearchForAgents from parameters and response handling.
    2. Remove imports of any *SearchForAgents types.
    3. Update metadata construction to exclude the SearchForAgents field.
    // After (v7.0.0):
    instance, err := client.AISearch.Instances.New(ctx, ai_search.InstanceNewParams{
        AccountID: cloudflare.F("account-id"),
        Metadata: cloudflare.F(ai_search.InstanceNewParamsMetadata{
            CreatedFromAISearchWizard: cloudflare.F(true),
            WorkerDomain:              cloudflare.F("worker_domain"),
        }),
    })
  6. Migrate Email Security TrustedDomains.New return type

    main

    The SettingTrustedDomainService.New method now returns a concrete *SettingTrustedDomainNewResponse instead of the union type *SettingTrustedDomainNewResponseUnion used in v6.

    Actions Needed:

    1. Replace SettingTrustedDomainNewResponseUnion with SettingTrustedDomainNewResponse in your code.
    2. Remove any union type assertions, as the response is now a concrete struct.
  7. Migrate resource_sharing Resources service in v7.4.0

    main

    In v7.4.0, the Update, Delete, and Get methods on the ResourceSharing.Resources service were removed, along with their associated response and parameter types.

    Remaining Methods:

    • client.ResourceSharing.Resources.New()
    • client.ResourceSharing.Resources.List()

    Removed Types:

    • ResourceUpdateResponse, ResourceDeleteResponse, ResourceGetResponse
    • ResourceUpdateParams, ResourceDeleteParams, ResourceGetParams

    Action: Remove all calls to Update, Delete, and Get on the Resources service and remove imports of the removed types.

  8. Migrate Email Security path parameters from v6 to v7

    main

    The path parameter types for Delete, Edit, and Get methods across several sub-resources have changed from int64 to string. Passing integer literals or int64 variables will cause compilation errors.

    Affected Services:

    • AllowPolicies (policyID)
    • BlockSenders (patternID)
    • Domains (domainID)
    • ImpersonationRegistry (impersonationRegistryID — formerly displayNameID)
    • TrustedDomains (trustedDomainID)

    Actions Needed:

    1. Convert all int64 path parameter arguments to string (e.g., using strconv.FormatInt() or string literals).
    2. For ImpersonationRegistry, update the parameter name from displayNameID to impersonationRegistryID in any named-argument usage.
    // After (v7.0.0):
    _, err := client.EmailSecurity.Settings.AllowPolicies.Delete(
        ctx,
        "2401",
        email_security.SettingAllowPolicyDeleteParams{
            AccountID: cloudflare.F("account_id"),
        },
    )
  9. Migrate realtime_kit.SessionService.GenerateSummaryOfTranscripts to v7.6.0

    main

    In v7.6.0, GenerateSummaryOfTranscripts() changed its return signature. It now returns both a response object and an error, whereas previously it only returned an error. You must update your code to capture the *SessionGenerateSummaryOfTranscriptsResponse value.

    // After (v7.6.0):
    resp, err := client.RealtimeKit.Sessions.GenerateSummaryOfTranscripts(ctx, "app-id", "session-id", realtime_kit.SessionGenerateSummaryOfTranscriptsParams{
        AccountID: cloudflare.F("account-id"),
    })
    // resp.Data contains the summary response