Movatterモバイル変換


[0]ホーム

URL:


cloudflare

packagemodule
v4.6.0Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2025 License:Apache-2.0Imports:104Imported by:20

Details

Repository

github.com/cloudflare/cloudflare-go

Links

README

Cloudflare Go API Library

Go Reference

The Cloudflare Go library provides convenient access to theCloudflare REST APIfrom applications written in Go.

It is generated withStainless.

Installation

import ("github.com/cloudflare/cloudflare-go/v4" // imported as cloudflare)

Or to pin the version:

go get -u 'github.com/cloudflare/cloudflare-go/v4@v4.6.0'

Requirements

This library requires Go 1.18+.

Usage

The full API of this library can be found inapi.md.

package mainimport ("context""fmt""github.com/cloudflare/cloudflare-go/v4""github.com/cloudflare/cloudflare-go/v4/option""github.com/cloudflare/cloudflare-go/v4/zones")func main() {client := cloudflare.NewClient(option.WithAPIToken("Sn3lZJTBX6kkg7OdcBUAxOO963GEIyGQqnFTOFYY"), // defaults to os.LookupEnv("CLOUDFLARE_API_TOKEN"))zone, err := client.Zones.New(context.TODO(), zones.ZoneNewParams{Account: cloudflare.F(zones.ZoneNewParamsAccount{ID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),}),Name: cloudflare.F("example.com"),Type: cloudflare.F(zones.TypeFull),})if err != nil {panic(err.Error())}fmt.Printf("%+v\n", zone.ID)}
Request fields

All request parameters are wrapped in a genericField type,which we use to distinguish zero values from null or omitted fields.

This prevents accidentally sending a zero value if you forget a required parameter,and enables explicitly sendingnull,false,'', or0 on optional parameters.Any field not specified is not sent.

To construct fields with values, use the helpersString(),Int(),Float(), or most commonly, the genericF[T]().To send a null, useNull[T](), and to send a nonconforming value, useRaw[T](any). For example:

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}),}
Response objects

All fields in response structs are value types (not pointers or wrappers).

If a given field isnull, not present, or invalid, the corresponding fieldwill simply be its zero value.

All response structs also include a specialJSON field, containing more detailedinformation about each property, which you can use like so:

if res.Name == "" {// true if `"name"` is either not present or explicitly nullres.JSON.Name.IsNull()// true if the `"name"` key was not present in the response JSON at allres.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}}

These.JSON structs also include anExtras map containingany properties in the json response that were not specifiedin the struct. This can be useful for API features not yetpresent in the SDK.

body := res.JSON.ExtraFields["my_unexpected_field"].Raw()
RequestOptions

This library uses the functional options pattern. Functions defined in theoption package return aRequestOption, which is a closure that mutates aRequestConfig. These options can be supplied to the client or at individualrequests. For example:

client := cloudflare.NewClient(// Adds a header to every request made by the clientoption.WithHeader("X-Some-Header", "custom_header_info"),)client.Zones.New(context.TODO(), ...,// Override the headeroption.WithHeader("X-Some-Header", "some_other_custom_header_info"),// Add an undocumented field to the request body, using sjson syntaxoption.WithJSONSet("some.json.path", map[string]string{"my": "object"}),)

See thefull list of request options.

Pagination

This library provides some conveniences for working with paginated list endpoints.

You can use.ListAutoPaging() methods to iterate through items across all pages:

iter := client.Accounts.ListAutoPaging(context.TODO(), accounts.AccountListParams{})// Automatically fetches more pages as needed.for iter.Next() {account := iter.Current()fmt.Printf("%+v\n", account)}if err := iter.Err(); err != nil {panic(err.Error())}

Or you can use simple.List() methods to fetch a single page and receive a standard response objectwith additional helper methods like.GetNextPage(), e.g.:

page, err := client.Accounts.List(context.TODO(), accounts.AccountListParams{})for page != nil {for _, account := range page.Result {fmt.Printf("%+v\n", account)}page, err = page.GetNextPage()}if err != nil {panic(err.Error())}
Errors

When the API returns a non-success status code, we return an error with type*cloudflare.Error. This contains theStatusCode,*http.Request, and*http.Response values of the request, as well as the JSON of the error body(much like other response objects in the SDK).

To handle errors, we recommend that you use theerrors.As pattern:

_, err := client.Zones.Get(context.TODO(), zones.ZoneGetParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),})if err != nil {var apierr *cloudflare.Errorif errors.As(err, &apierr) {println(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP requestprintln(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response}panic(err.Error()) // GET "/zones/{zone_id}": 400 Bad Request { ... }}

When other errors occur, they are returned unwrapped; for example,if HTTP transport fails, you might receive*url.Error wrapping*net.OpError.

Timeouts

Requests do not time out by default; use context to configure a timeout for a request lifecycle.

Note that if a request isretried, the context timeout does not start over.To set a per-retry timeout, useoption.WithRequestTimeout().

// This sets the timeout for the request, including all the retries.ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)defer cancel()client.Zones.Edit(ctx,zones.ZoneEditParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),},// This sets the per-retry timeoutoption.WithRequestTimeout(20*time.Second),)
File uploads

Request parameters that correspond to file uploads in multipart requests are typed asparam.Field[io.Reader]. The contents of theio.Reader will by default be sent as a multipart formpart with the file name of "anonymous_file" and content-type of "application/octet-stream".

The file name and content-type can be customized by implementingName() string orContentType() string on the run-time type ofio.Reader. Note thatos.File implementsName() string, so afile returned byos.Open will be sent with the file name on disk.

We also provide a helpercloudflare.FileParam(reader io.Reader, filename string, contentType string)which can be used to wrap anyio.Reader with the appropriate file name and content type.

// A file from the file systemfile, err := os.Open("/path/to/file")api_gateway.UserSchemaNewParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File:   cloudflare.F[io.Reader](file),Kind:   cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}// A file from a stringapi_gateway.UserSchemaNewParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File:   cloudflare.F[io.Reader](strings.NewReader("my file contents")),Kind:   cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}// With a custom filename and contentTypeapi_gateway.UserSchemaNewParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),File:   cloudflare.FileParam(strings.NewReader(`{"hello": "foo"}`), "file.go", "application/json"),Kind:   cloudflare.F(api_gateway.UserSchemaNewParamsKindOpenAPIV3),}
Retries

Certain errors will be automatically retried 2 times by default, with a short exponential backoff.We retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,and >=500 Internal errors.

You can use theWithMaxRetries option to configure or disable this:

// Configure the default for all requests:client := cloudflare.NewClient(option.WithMaxRetries(0), // default is 2)// Override per-request:client.Zones.Get(context.TODO(),zones.ZoneGetParams{ZoneID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),},option.WithMaxRetries(5),)
Accessing raw response data (e.g. response headers)

You can access the raw HTTP response data by using theoption.WithResponseInto() request option. This is useful whenyou need to examine response headers, status codes, or other details.

// Create a variable to store the HTTP responsevar response *http.Responsezone, err := client.Zones.New(context.TODO(),zones.ZoneNewParams{Account: cloudflare.F(zones.ZoneNewParamsAccount{ID: cloudflare.F("023e105f4ecef8ad9ca31a8372d0c353"),}),Name: cloudflare.F("example.com"),Type: cloudflare.F(zones.TypeFull),},option.WithResponseInto(&response),)if err != nil {// handle error}fmt.Printf("%+v\n", zone)fmt.Printf("Status Code: %d\n", response.StatusCode)fmt.Printf("Headers: %+#v\n", response.Header)
Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumentedendpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, you can useclient.Get,client.Post, and other HTTP verbs.RequestOptions on the client, such as retries, will be respected when making these requests.

var (    // params can be an io.Reader, a []byte, an encoding/json serializable object,    // or a "…Params" struct defined in this library.    params map[string]interface{}    // result can be an []byte, *http.Response, a encoding/json deserializable object,    // or a model defined in this library.    result *http.Response)err := client.Post(context.Background(), "/unspecified", params, &result)if err != nil {    …}
Undocumented request params

To make requests using undocumented parameters, you may use either theoption.WithQuerySet()or theoption.WithJSONSet() methods.

params := FooNewParams{    ID:   cloudflare.F("id_xxxx"),    Data: cloudflare.F(FooNewParamsData{        FirstName: cloudflare.F("John"),    }),}client.Foo.New(context.Background(), params, option.WithJSONSet("data.last_name", "Doe"))
Undocumented response properties

To access undocumented response properties, you may either access the raw JSON of the response as a stringwithresult.JSON.RawJSON(), or get the raw JSON of a particular field on the result withresult.JSON.Foo.Raw().

Any fields that are not present on the response struct will be saved and can be accessed byresult.JSON.ExtraFields() which returns the extra fields as amap[string]Field.

Middleware

We provideoption.WithMiddleware which applies the givenmiddleware to requests.

func Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {// Before the requeststart := time.Now()LogReq(req)// Forward the request to the next handlerres, err = next(req)// Handle stuff after the requestend := time.Now()LogRes(res, err, start - end)    return res, err}client := cloudflare.NewClient(option.WithMiddleware(Logger),)

When multiple middlewares are provided as variadic arguments, the middlewaresare applied left to right. Ifoption.WithMiddleware is givenmultiple times, for example first in the client then the method, themiddleware in the client will run first and the middleware given in the methodwill run next.

You may also replace the defaulthttp.Client withoption.WithHTTPClient(client). Only one http client isaccepted (this overwrites any previous client) and receives requests after anymiddleware has been applied.

Semantic versioning

This package generally followsSemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use.(Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

Maintenance

This SDK is actively maintained, however, many issues are tracked outside of GitHub on internal Cloudflare systems. Members of the community are welcome to join and discuss your issues during our twice monthly triage meetings. For urgent issues, please contactCloudflare support.

Contributing

Seethe contributing documentation.

Documentation

Index

Constants

View Source
const AuditLogActorTypeAdmin =shared.AuditLogActorTypeAdmin

This is an alias to an internal value.

View Source
const AuditLogActorTypeCloudflare =shared.AuditLogActorTypeCloudflare

This is an alias to an internal value.

View Source
const AuditLogActorTypeUser =shared.AuditLogActorTypeUser

This is an alias to an internal value.

View Source
const CertificateCADigicert =shared.CertificateCADigicert

This is an alias to an internal value.

View Source
const CertificateCAGoogle =shared.CertificateCAGoogle

This is an alias to an internal value.

View Source
const CertificateCALetsEncrypt =shared.CertificateCALetsEncrypt

This is an alias to an internal value.

View Source
const CertificateCASSLCom =shared.CertificateCASSLCom

This is an alias to an internal value.

View Source
const CertificateRequestTypeKeylessCertificate =shared.CertificateRequestTypeKeylessCertificate

This is an alias to an internal value.

View Source
const CertificateRequestTypeOriginECC =shared.CertificateRequestTypeOriginECC

This is an alias to an internal value.

View Source
const CertificateRequestTypeOriginRSA =shared.CertificateRequestTypeOriginRSA

This is an alias to an internal value.

View Source
const CloudflareTunnelStatusDegraded =shared.CloudflareTunnelStatusDegraded

This is an alias to an internal value.

View Source
const CloudflareTunnelStatusDown =shared.CloudflareTunnelStatusDown

This is an alias to an internal value.

View Source
const CloudflareTunnelStatusHealthy =shared.CloudflareTunnelStatusHealthy

This is an alias to an internal value.

View Source
const CloudflareTunnelStatusInactive =shared.CloudflareTunnelStatusInactive

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeCNI =shared.CloudflareTunnelTunTypeCNI

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeCfdTunnel =shared.CloudflareTunnelTunTypeCfdTunnel

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeGRE =shared.CloudflareTunnelTunTypeGRE

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeIPSec =shared.CloudflareTunnelTunTypeIPSec

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeMagic =shared.CloudflareTunnelTunTypeMagic

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeWARP =shared.CloudflareTunnelTunTypeWARP

This is an alias to an internal value.

View Source
const CloudflareTunnelTunTypeWARPConnector =shared.CloudflareTunnelTunTypeWARPConnector

This is an alias to an internal value.

View Source
const MemberPoliciesAccessAllow =shared.MemberPoliciesAccessAllow

This is an alias to an internal value.

View Source
const MemberPoliciesAccessDeny =shared.MemberPoliciesAccessDeny

This is an alias to an internal value.

View Source
const MemberStatusAccepted =shared.MemberStatusAccepted

This is an alias to an internal value.

View Source
const MemberStatusPending =shared.MemberStatusPending

This is an alias to an internal value.

View Source
const RatePlanIDBusiness =shared.RatePlanIDBusiness

This is an alias to an internal value.

View Source
const RatePlanIDEnterprise =shared.RatePlanIDEnterprise

This is an alias to an internal value.

View Source
const RatePlanIDFree =shared.RatePlanIDFree

This is an alias to an internal value.

View Source
const RatePlanIDLite =shared.RatePlanIDLite

This is an alias to an internal value.

View Source
const RatePlanIDPartnersBusiness =shared.RatePlanIDPartnersBusiness

This is an alias to an internal value.

View Source
const RatePlanIDPartnersEnterprise =shared.RatePlanIDPartnersEnterprise

This is an alias to an internal value.

View Source
const RatePlanIDPartnersFree =shared.RatePlanIDPartnersFree

This is an alias to an internal value.

View Source
const RatePlanIDPartnersPro =shared.RatePlanIDPartnersPro

This is an alias to an internal value.

View Source
const RatePlanIDPro =shared.RatePlanIDPro

This is an alias to an internal value.

View Source
const RatePlanIDProPlus =shared.RatePlanIDProPlus

This is an alias to an internal value.

View Source
const SortDirectionAsc =shared.SortDirectionAsc

This is an alias to an internal value.

View Source
const SortDirectionDesc =shared.SortDirectionDesc

This is an alias to an internal value.

View Source
const SubscriptionFrequencyMonthly =shared.SubscriptionFrequencyMonthly

This is an alias to an internal value.

View Source
const SubscriptionFrequencyQuarterly =shared.SubscriptionFrequencyQuarterly

This is an alias to an internal value.

View Source
const SubscriptionFrequencyWeekly =shared.SubscriptionFrequencyWeekly

This is an alias to an internal value.

View Source
const SubscriptionFrequencyYearly =shared.SubscriptionFrequencyYearly

This is an alias to an internal value.

View Source
const SubscriptionStateAwaitingPayment =shared.SubscriptionStateAwaitingPayment

This is an alias to an internal value.

View Source
const SubscriptionStateCancelled =shared.SubscriptionStateCancelled

This is an alias to an internal value.

View Source
const SubscriptionStateExpired =shared.SubscriptionStateExpired

This is an alias to an internal value.

View Source
const SubscriptionStateFailed =shared.SubscriptionStateFailed

This is an alias to an internal value.

View Source
const SubscriptionStatePaid =shared.SubscriptionStatePaid

This is an alias to an internal value.

View Source
const SubscriptionStateProvisioned =shared.SubscriptionStateProvisioned

This is an alias to an internal value.

View Source
const SubscriptionStateTrial =shared.SubscriptionStateTrial

This is an alias to an internal value.

View Source
const TokenPolicyEffectAllow =shared.TokenPolicyEffectAllow

This is an alias to an internal value.

View Source
const TokenPolicyEffectDeny =shared.TokenPolicyEffectDeny

This is an alias to an internal value.

View Source
const TokenStatusActive =shared.TokenStatusActive

This is an alias to an internal value.

View Source
const TokenStatusDisabled =shared.TokenStatusDisabled

This is an alias to an internal value.

View Source
const TokenStatusExpired =shared.TokenStatusExpired

This is an alias to an internal value.

Variables

This section is empty.

Functions

funcBool

func Bool(valuebool)param.Field[bool]

Bool is a param field helper which helps specify bools.

funcDefaultClientOptionsadded inv4.2.0

func DefaultClientOptions() []option.RequestOption

DefaultClientOptions read from the environment (CLOUDFLARE_API_KEY,CLOUDFLARE_API_USER_SERVICE_KEY, CLOUDFLARE_API_TOKEN, CLOUDFLARE_EMAIL,CLOUDFLARE_BASE_URL). This should be used to initialize new clients.

funcF

func F[Tany](value T)param.Field[T]

F is a param field helper used to initialize aparam.Field generic struct.This helps specify null, zero values, and overrides, as well as normal values.You can read more about this in ourREADME.

funcFileParam

func FileParam(readerio.Reader, filenamestring, contentTypestring)param.Field[io.Reader]

FileParam is a param field helper which helps files with a mime content-type.

funcFloat

func Float(valuefloat64)param.Field[float64]

Float is a param field helper which helps specify floats.

funcInt

func Int(valueint64)param.Field[int64]

Int is a param field helper which helps specify integers. This isparticularly helpful when specifying integer constants for fields.

funcNull

func Null[Tany]()param.Field[T]

Null is a param field helper which explicitly sends null to the API.

funcRaw

func Raw[Tany](valueany)param.Field[T]

Raw is a param field helper for specifying values for fields when thetype you are looking to send is different from the type that is specified inthe SDK. For example, if the type of the field is an integer, but you wantto send a float, you could do that by setting the corresponding field withRaw[int](0.5).

funcString

func String(valuestring)param.Field[string]

String is a param field helper which helps specify strings.

Types

typeASN

type ASN =shared.ASN

This is an alias to an internal type.

typeASNParam

type ASNParam =shared.ASNParam

This is an alias to an internal type.

typeAuditLog

type AuditLog =shared.AuditLog

This is an alias to an internal type.

typeAuditLogAction

type AuditLogAction =shared.AuditLogAction

This is an alias to an internal type.

typeAuditLogActor

type AuditLogActor =shared.AuditLogActor

This is an alias to an internal type.

typeAuditLogActorType

type AuditLogActorType =shared.AuditLogActorType

The type of actor, whether a User, Cloudflare Admin, or an Automated System.

This is an alias to an internal type.

typeAuditLogOwner

type AuditLogOwner =shared.AuditLogOwner

This is an alias to an internal type.

typeAuditLogResource

type AuditLogResource =shared.AuditLogResource

This is an alias to an internal type.

typeCertificateCA

type CertificateCA =shared.CertificateCA

The Certificate Authority that will issue the certificate

This is an alias to an internal type.

typeCertificateRequestType

type CertificateRequestType =shared.CertificateRequestType

Signature type desired on certificate ("origin-rsa" (rsa), "origin-ecc" (ecdsa),or "keyless-certificate" (for Keyless SSL servers).

This is an alias to an internal type.

typeClient

type Client struct {Options                []option.RequestOptionAccounts               *accounts.AccountServiceOriginCACertificates   *origin_ca_certificates.OriginCACertificateServiceIPs                    *ips.IPServiceMemberships            *memberships.MembershipServiceUser                   *user.UserServiceZones                  *zones.ZoneServiceLoadBalancers          *load_balancers.LoadBalancerServiceCache                  *cache.CacheServiceSSL                    *ssl.SSLServiceACM                    *acm.ACMServiceArgo                   *argo.ArgoServiceCertificateAuthorities *certificate_authorities.CertificateAuthorityServiceClientCertificates     *client_certificates.ClientCertificateServiceCustomCertificates     *custom_certificates.CustomCertificateServiceCustomHostnames        *custom_hostnames.CustomHostnameServiceCustomNameservers      *custom_nameservers.CustomNameserverServiceDNSFirewall            *dns_firewall.DNSFirewallServiceDNS                    *dns.DNSServiceEmailSecurity          *email_security.EmailSecurityServiceEmailRouting           *email_routing.EmailRoutingService// Deprecated: The Filters API is deprecated in favour of using the Ruleset Engine.// See//https://developers.cloudflare.com/fundamentals/api/reference/deprecations/#firewall-rules-api-and-filters-api// for full details.Filters             *filters.FilterServiceFirewall            *firewall.FirewallServiceHealthchecks        *healthchecks.HealthcheckServiceKeylessCertificates *keyless_certificates.KeylessCertificateServiceLogpush             *logpush.LogpushServiceLogs                *logs.LogServiceOriginTLSClientAuth *origin_tls_client_auth.OriginTLSClientAuthServicePageRules           *page_rules.PageRuleService// Deprecated: Rate limiting API is deprecated in favour of using the Ruleset// Engine. See//https://developers.cloudflare.com/fundamentals/api/reference/deprecations/#rate-limiting-api-previous-version// for full details.RateLimits                  *rate_limits.RateLimitServiceWaitingRooms                *waiting_rooms.WaitingRoomServiceWeb3                        *web3.Web3ServiceWorkers                     *workers.WorkerServiceKV                          *kv.KVServiceDurableObjects              *durable_objects.DurableObjectServiceQueues                      *queues.QueueServiceAPIGateway                  *api_gateway.APIGatewayServiceManagedTransforms           *managed_transforms.ManagedTransformServicePageShield                  *page_shield.PageShieldServiceRulesets                    *rulesets.RulesetServiceURLNormalization            *url_normalization.URLNormalizationServiceSpectrum                    *spectrum.SpectrumServiceAddressing                  *addressing.AddressingServiceAuditLogs                   *audit_logs.AuditLogServiceBilling                     *billing.BillingServiceBrandProtection             *brand_protection.BrandProtectionServiceDiagnostics                 *diagnostics.DiagnosticServiceImages                      *images.ImageServiceIntel                       *intel.IntelServiceMagicTransit                *magic_transit.MagicTransitServiceMagicNetworkMonitoring      *magic_network_monitoring.MagicNetworkMonitoringServiceMagicCloudNetworking        *magic_cloud_networking.MagicCloudNetworkingServiceNetworkInterconnects        *network_interconnects.NetworkInterconnectServiceMTLSCertificates            *mtls_certificates.MTLSCertificateServicePages                       *pages.PageServiceRegistrar                   *registrar.RegistrarServiceRequestTracers              *request_tracers.RequestTracerServiceRules                       *rules.RuleServiceStream                      *stream.StreamServiceAlerting                    *alerting.AlertingServiceD1                          *d1.D1ServiceR2                          *r2.R2ServiceWorkersForPlatforms         *workers_for_platforms.WorkersForPlatformServiceZeroTrust                   *zero_trust.ZeroTrustServiceTurnstile                   *turnstile.TurnstileServiceHyperdrive                  *hyperdrive.HyperdriveServiceRUM                         *rum.RUMServiceVectorize                   *vectorize.VectorizeServiceURLScanner                  *url_scanner.URLScannerServiceRadar                       *radar.RadarServiceBotManagement               *bot_management.BotManagementServiceOriginPostQuantumEncryption *origin_post_quantum_encryption.OriginPostQuantumEncryptionServiceZaraz                       *zaraz.ZarazServiceSpeed                       *speed.SpeedServiceDCVDelegation               *dcv_delegation.DCVDelegationServiceHostnames                   *hostnames.HostnameServiceSnippets                    *snippets.SnippetServiceCalls                       *calls.CallServiceCloudforceOne               *cloudforce_one.CloudforceOneServiceAIGateway                   *ai_gateway.AIGatewayServiceIAM                         *iam.IAMServiceCloudConnector              *cloud_connector.CloudConnectorServiceBotnetFeed                  *botnet_feed.BotnetFeedServiceSecurityTXT                 *security_txt.SecurityTXTServiceWorkflows                   *workflows.WorkflowServiceResourceSharing             *resource_sharing.ResourceSharingServiceLeakedCredentialChecks      *leaked_credential_checks.LeakedCredentialCheckServiceContentScanning             *content_scanning.ContentScanningServiceAbuseReports                *abuse_reports.AbuseReportServiceAI                          *ai.AIServiceSecurityCenter              *security_center.SecurityCenterServiceBrowserRendering            *browser_rendering.BrowserRenderingServiceCustomPages                 *custom_pages.CustomPageServiceSecretsStore                *secrets_store.SecretsStoreServicePipelines                   *pipelines.PipelineServiceSchemaValidation            *schema_validation.SchemaValidationService}

Client creates a struct with services and top level methods that help withinteracting with the cloudflare API. You should not instantiate this clientdirectly, and instead use theNewClient method instead.

funcNewClient

func NewClient(opts ...option.RequestOption) (r *Client)

NewClient generates a new client with the default option read from theenvironment (CLOUDFLARE_API_KEY, CLOUDFLARE_API_USER_SERVICE_KEY,CLOUDFLARE_API_TOKEN, CLOUDFLARE_EMAIL, CLOUDFLARE_BASE_URL). The option passedin as arguments are applied after these default arguments, and all option willbe passed down to the services and requests that this client makes.

func (*Client)Delete

func (r *Client) Delete(ctxcontext.Context, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Delete makes a DELETE request with the given URL, params, and optionallydeserializes to a response. See [Execute] documentation on the params andresponse.

func (*Client)Execute

func (r *Client) Execute(ctxcontext.Context, methodstring, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Execute makes a request with the given context, method, URL, request params,response, and request options. This is useful for hitting undocumented endpointswhile retaining the base URL, auth, retries, and other options from the client.

If a byte slice or anio.Reader is supplied to params, it will be used as-isfor the request body.

The params is by default serialized into the body usingencoding/json. If yourtype implements a MarshalJSON function, it will be used instead to serialize therequest. If a URLQuery method is implemented, the returned [url.Values] will beused as query strings to the url.

If your params struct usesparam.Field, you must provide either [MarshalJSON],[URLQuery], and/or [MarshalForm] functions. It is undefined behavior to use astruct usesparam.Field without specifying how it is serialized.

Any "…Params" object defined in this library can be used as the requestargument. Note that 'path' arguments will not be forwarded into the url.

The response body will be deserialized into the res variable, depending on itstype:

  • A pointer to a*http.Response is populated by the raw response.
  • A pointer to a byte array will be populated with the contents of the requestbody.
  • A pointer to any other type uses this library's default JSON decoding, whichrespects UnmarshalJSON if it is defined on the type.
  • A nil value will not read the response body.

For even greater flexibility, seeoption.WithResponseInto andoption.WithResponseBodyInto.

func (*Client)Get

func (r *Client) Get(ctxcontext.Context, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Get makes a GET request with the given URL, params, and optionally deserializesto a response. See [Execute] documentation on the params and response.

func (*Client)Patch

func (r *Client) Patch(ctxcontext.Context, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Patch makes a PATCH request with the given URL, params, and optionallydeserializes to a response. See [Execute] documentation on the params andresponse.

func (*Client)Post

func (r *Client) Post(ctxcontext.Context, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Post makes a POST request with the given URL, params, and optionallydeserializes to a response. See [Execute] documentation on the params andresponse.

func (*Client)Put

func (r *Client) Put(ctxcontext.Context, pathstring, params interface{}, res interface{}, opts ...option.RequestOption)error

Put makes a PUT request with the given URL, params, and optionally deserializesto a response. See [Execute] documentation on the params and response.

typeCloudflareTunnel

type CloudflareTunnel =shared.CloudflareTunnel

A Cloudflare Tunnel that connects your origin to Cloudflare's edge.

This is an alias to an internal type.

typeCloudflareTunnelConnection

type CloudflareTunnelConnection =shared.CloudflareTunnelConnection

This is an alias to an internal type.

typeCloudflareTunnelStatus

type CloudflareTunnelStatus =shared.CloudflareTunnelStatus

The status of the tunnel. Valid values are `inactive` (tunnel has never beenrun), `degraded` (tunnel is active and able to serve traffic but in an unhealthystate), `healthy` (tunnel is active and able to serve traffic), or `down`(tunnel can not serve traffic as it has no connections to the Cloudflare Edge).

This is an alias to an internal type.

typeCloudflareTunnelTunType

type CloudflareTunnelTunType =shared.CloudflareTunnelTunType

The type of tunnel.

This is an alias to an internal type.

typeError

type Error =apierror.Error

typeErrorData

type ErrorData =shared.ErrorData

This is an alias to an internal type.

typeErrorDataSourceadded inv4.2.0

type ErrorDataSource =shared.ErrorDataSource

This is an alias to an internal type.

typeMember

type Member =shared.Member

This is an alias to an internal type.

typeMemberPoliciesAccess

type MemberPoliciesAccess =shared.MemberPoliciesAccess

Allow or deny operations against the resources.

This is an alias to an internal type.

typeMemberPoliciesPermissionGroup

type MemberPoliciesPermissionGroup =shared.MemberPoliciesPermissionGroup

A named group of permissions that map to a group of operations againstresources.

This is an alias to an internal type.

typeMemberPoliciesPermissionGroupsMeta

type MemberPoliciesPermissionGroupsMeta =shared.MemberPoliciesPermissionGroupsMeta

Attributes associated to the permission group.

This is an alias to an internal type.

typeMemberPoliciesResourceGroup

type MemberPoliciesResourceGroup =shared.MemberPoliciesResourceGroup

A group of scoped resources.

This is an alias to an internal type.

typeMemberPoliciesResourceGroupsMeta

type MemberPoliciesResourceGroupsMeta =shared.MemberPoliciesResourceGroupsMeta

Attributes associated to the resource group.

This is an alias to an internal type.

typeMemberPoliciesResourceGroupsScope

type MemberPoliciesResourceGroupsScope =shared.MemberPoliciesResourceGroupsScope

A scope is a combination of scope objects which provides additional context.

This is an alias to an internal type.

typeMemberPoliciesResourceGroupsScopeObject

type MemberPoliciesResourceGroupsScopeObject =shared.MemberPoliciesResourceGroupsScopeObject

A scope object represents any resource that can have actions applied againstinvite.

This is an alias to an internal type.

typeMemberPolicy

type MemberPolicy =shared.MemberPolicy

This is an alias to an internal type.

typeMemberStatus

type MemberStatus =shared.MemberStatus

A member's status in the account.

This is an alias to an internal type.

typeMemberUser

type MemberUser =shared.MemberUser

Details of the user associated to the membership.

This is an alias to an internal type.

typePermission

type Permission =shared.Permission

This is an alias to an internal type.

typePermissionGrant

type PermissionGrant =shared.PermissionGrant

This is an alias to an internal type.

typePermissionGrantParam

type PermissionGrantParam =shared.PermissionGrantParam

This is an alias to an internal type.

typeRatePlan

type RatePlan =shared.RatePlan

The rate plan applied to the subscription.

This is an alias to an internal type.

typeRatePlanIDadded inv4.1.0

type RatePlanID =shared.RatePlanID

The ID of the rate plan.

This is an alias to an internal type.

typeRatePlanParam

type RatePlanParam =shared.RatePlanParam

The rate plan applied to the subscription.

This is an alias to an internal type.

typeResponseInfo

type ResponseInfo =shared.ResponseInfo

This is an alias to an internal type.

typeResponseInfoSourceadded inv4.3.0

type ResponseInfoSource =shared.ResponseInfoSource

This is an alias to an internal type.

typeRole

type Role =shared.Role

This is an alias to an internal type.

typeRoleParam

type RoleParam =shared.RoleParam

This is an alias to an internal type.

typeRolePermissions

type RolePermissions =shared.RolePermissions

This is an alias to an internal type.

typeRolePermissionsParam

type RolePermissionsParam =shared.RolePermissionsParam

This is an alias to an internal type.

typeSortDirection

type SortDirection =shared.SortDirection

Direction to order DNS records in.

This is an alias to an internal type.

typeSubscription

type Subscription =shared.Subscription

This is an alias to an internal type.

typeSubscriptionFrequency

type SubscriptionFrequency =shared.SubscriptionFrequency

How often the subscription is renewed automatically.

This is an alias to an internal type.

typeSubscriptionParam

type SubscriptionParam =shared.SubscriptionParam

This is an alias to an internal type.

typeSubscriptionState

type SubscriptionState =shared.SubscriptionState

The state that the subscription is in.

This is an alias to an internal type.

typeToken

type Token =shared.Token

This is an alias to an internal type.

typeTokenCondition

type TokenCondition =shared.TokenCondition

This is an alias to an internal type.

typeTokenConditionCIDRList

type TokenConditionCIDRList =shared.TokenConditionCIDRList

IPv4/IPv6 CIDR.

This is an alias to an internal type.

typeTokenConditionCIDRListParam

type TokenConditionCIDRListParam =shared.TokenConditionCIDRListParam

IPv4/IPv6 CIDR.

This is an alias to an internal type.

typeTokenConditionParam

type TokenConditionParam =shared.TokenConditionParam

This is an alias to an internal type.

typeTokenConditionRequestIP

type TokenConditionRequestIP =shared.TokenConditionRequestIP

Client IP restrictions.

This is an alias to an internal type.

typeTokenConditionRequestIPParam

type TokenConditionRequestIPParam =shared.TokenConditionRequestIPParam

Client IP restrictions.

This is an alias to an internal type.

typeTokenParam

type TokenParam =shared.TokenParam

This is an alias to an internal type.

typeTokenPolicy

type TokenPolicy =shared.TokenPolicy

This is an alias to an internal type.

typeTokenPolicyEffect

type TokenPolicyEffect =shared.TokenPolicyEffect

Allow or deny operations against the resources.

This is an alias to an internal type.

typeTokenPolicyParam

type TokenPolicyParam =shared.TokenPolicyParam

This is an alias to an internal type.

typeTokenPolicyPermissionGroup

type TokenPolicyPermissionGroup =shared.TokenPolicyPermissionGroup

A named group of permissions that map to a group of operations againstresources.

This is an alias to an internal type.

typeTokenPolicyPermissionGroupParam

type TokenPolicyPermissionGroupParam =shared.TokenPolicyPermissionGroupParam

A named group of permissions that map to a group of operations againstresources.

This is an alias to an internal type.

typeTokenPolicyPermissionGroupsMeta

type TokenPolicyPermissionGroupsMeta =shared.TokenPolicyPermissionGroupsMeta

Attributes associated to the permission group.

This is an alias to an internal type.

typeTokenPolicyPermissionGroupsMetaParam

type TokenPolicyPermissionGroupsMetaParam =shared.TokenPolicyPermissionGroupsMetaParam

Attributes associated to the permission group.

This is an alias to an internal type.

typeTokenPolicyResourcesMapadded inv4.6.0

type TokenPolicyResourcesMap =shared.TokenPolicyResourcesMap

A nested permission grant for further scoping.

This is an alias to an internal type.

typeTokenPolicyResourcesMapParamadded inv4.6.0

type TokenPolicyResourcesMapParam =shared.TokenPolicyResourcesMapParam

A nested permission grant for further scoping.

This is an alias to an internal type.

typeTokenPolicyResourcesUnionadded inv4.6.0

type TokenPolicyResourcesUnion =shared.TokenPolicyResourcesUnion

A simple wildcard permission, e.g., "\*".

This is an alias to an internal type.

typeTokenPolicyResourcesUnionParamadded inv4.6.0

type TokenPolicyResourcesUnionParam =shared.TokenPolicyResourcesUnionParam

A simple wildcard permission, e.g., "\*".

This is an alias to an internal type.

typeTokenStatus

type TokenStatus =shared.TokenStatus

Status of the token.

This is an alias to an internal type.

typeTokenValue

type TokenValue =shared.TokenValue

The token value.

This is an alias to an internal type.

Source Files

View all Source files

Directories

PathSynopsis
packages

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp