csbgo

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 20 Imported by: 0

README

csbgo

Go Reference

纯 Go 标准库实现的 CSB(云服务总线)HTTP 服务调用客户端:按 CSB 规范自动完成 HMAC-SHA1 签名,无第三方依赖,要求 Go 1.27+。

go get github.com/gomodb/csbgo

快速开始

client := csbgo.New(
    csbgo.WithBaseURL("http://broker.example.com/CSB"), // CSB 唯一端点
    csbgo.WithAK("access-key"),
    csbgo.WithSK("secret-key"),
    csbgo.WithTimeout(10*time.Second),
)

resp, err := client.Do(ctx,
    csbgo.NewRequest(csbgo.MethodPost).
        WithAPI("MyService").
        WithVersion("v1").
        WithQuery("name", "wiseking").
        WithForm("p1", "dog"),
)
if err != nil {
    return err
}
log.Println(resp.ToString())

WithAPI / WithVersion 也可设在 Client 上作为默认值。Client 创建后不可变、并发安全,适合设为包级变量复用;Request 不是并发安全的,每次调用新建,或用 Clone() 从模板派生。

API

New(opts ...Option) *Client
Option 说明
WithBaseURL CSB 端点(必填,单个端点)
WithAK / WithSK access key / secret key(要么都给,要么都不给=匿名)
WithAPI / WithVersion 默认 API 名 / 版本
WithTimeout 总超时(默认 60s)
WithHTTPClient / WithTransport 自定义 *http.Client / http.RoundTripper(可用 RoundTripFunc 适配函数)
WithUserAgent User-Agent(默认 csbBroker)
WithDebug / WithLogger 调试日志开关与出口(接受任意 *slog.Logger)
WithStatusCheck 状态码判定:默认仅 2xx,AcceptStatus(200, 201) 指定码,AcceptAnyStatus 关闭
WithRetries 等 见「重试」

WithHTTPClient(nil) / WithLogger(nil) / WithStatusCheck(nil) 表示恢复默认值。

NewRequest(method) *Request

method 仅支持 MethodGet / MethodPost。链式方法:

  • 参数:WithQuery / WithQueryInt / WithQueries / WithQueryValues,WithForm / WithForms / WithFormValues
  • 其他:WithHeader / WithHeaders,WithBody(contentType, body) / WithJSON(v)(仅 POST)
  • URL:WithHost / WithPath / WithPathf(默认使用 Client 的 baseURL)
  • 按请求覆盖:WithAK / WithSK / WithMethod / WithStatusCheck 及整套重试选项

WithQuery / WithForm 重复设置同一 key 会覆盖;需要重复参数时用 WithQueryValues(key, v1, v2, ...)。

_api_* 是 SDK 保留字段,通过 WithQuery / WithForm / WithHeader 或 base URL query 传入会报错。

Do / DoAs
resp, err := client.Do(ctx, req)          // 原始响应
user, err := client.DoAs[User](ctx, req)  // 一步请求 + JSON 解码

默认只接受 2xx,否则返回 *StatusError。Response 提供 ToString() / ToBytes() / ToJSON(&v) / OK();需要同时拿到响应头时用 Do + resp.ToJSON(&out)。

错误处理

所有诊断信息都挂在 *Error 上,*StatusError 只是「状态码不被接受」的标记(Response() 是 Err.Response 的简写):

var ce *csbgo.Error
if errors.As(err, &ce) {
    ce.Code        // CSB 错误码(csbgo.Code)
    ce.Message     // 错误描述
    ce.RequestID   // 便于对账定位
    ce.Request     // 实际发出的请求;nil = 尚未构造(校验类失败)
    ce.Response    // 收到的响应;nil = 传输失败
}

ce.Request 含 Method、URL(最终 URL)、Header(secret key 与 signature 已脱敏)、BodyLen(不保存请求体内容)。

CSB 通过逃逸码返回失败,真实错误码写在描述里:[504] api name not found(阶段 2,CSB 处理失败)、[800][60] service not found(阶段 3,服务提供端失败)。SDK 会解析并填入 Code / ProviderCode / Message,ProviderError() 判断是否阶段 3。全部错误码见 csbgo.Code 常量,描述用 Code.String()。

非 CSB 响应体(如网关 HTML 错误页)不含错误码,此时 Code 为 0,截断后的正文作为 Message 保留。

参数发送规则

方法 Query Form 请求体
GET 追加到 URL 追加到 URL 无
POST(无显式 body) 追加到 URL — form 编码
POST + WithJSON / WithBody 追加到 URL 追加到 URL JSON / 原始字节

无论走哪条路径,query 与 form 参数(含重复参数)都会进入签名,签名参数集与线上送达参数集保持一致。

重试

默认关闭。

client := csbgo.New(
    csbgo.WithBaseURL("http://broker.example.com/CSB"),
    csbgo.WithAK("ak"), csbgo.WithSK("sk"),
    csbgo.WithRetries(3),
    csbgo.WithRetryBackoff(200*time.Millisecond), // 退避起点,逐次翻倍(默认 100ms)
    csbgo.WithMaxRetryDelay(5*time.Second),       // 单次等待上限(默认 30s)
    csbgo.WithJitter(csbgo.FullJitter),           // 默认;另有 EqualJitter / NoJitter
)
  • 触发条件:传输错误、5xx、429;context 取消或超时永不重试
  • Retry-After 响应头(秒数或 HTTP-date)优先采用,仍受 WithMaxRetryDelay 约束
  • WithRetryIf(pred) 自定义是否重试;WithRetryDelay(fn) 完全替换退避;WithOnRetry(fn) 用于日志或指标
  • 以上重试选项均可在 Request 上按请求覆盖

说明

  • JSON:使用 Go 1.27 的 encoding/json/v2。与 v1 的差异:重复键与非法 UTF-8 会直接报错。
  • 日志:WithDebug(true) 输出结构化日志(csb: http request、csb: signed request),签名已脱敏;WithLogger 可传入现有 *slog.Logger 复用同一套 handler。

License

MIT

Documentation

Overview

Package csbgo implements a minimal, dependency-free client for invoking HTTP services published through Alibaba Cloud CSB (Cloud Service Bus).

Index

Examples

Constants

View Source
const (
	MethodGet  = http.MethodGet
	MethodPost = http.MethodPost
)

Method and content-type convenience constants.

View Source
const (
	ContentTypeJSON   = "application/json"
	ContentTypeForm   = "application/x-www-form-urlencoded"
	ContentTypeBinary = "application/octet-stream"
)

Variables

This section is empty.

Functions

func AcceptAnyStatus added in v0.5.1

func AcceptAnyStatus(int) bool

AcceptAnyStatus accepts every status code. Pass it to WithStatusCheck to disable status checking.

func AcceptStatus

func AcceptStatus(codes ...int) func(int) bool

AcceptStatus returns a status checker that accepts exactly the given codes. Pass it to WithStatusCheck to replace the default 2xx-only check.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client invokes CSB-published HTTP services. It is safe for concurrent use once created: Do does not mutate the client. Create one Client per broker (or per credential set) and reuse it for many calls.

Example

ExampleClient configures a Client and invokes a CSB-published service.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/gomodb/csbgo"
)

func main() {
	client := csbgo.New(
		csbgo.WithBaseURL("http://broker.example.com/CSB"), // the single CSB endpoint
		csbgo.WithAK("your-access-key"),
		csbgo.WithSK("your-secret-key"),
		csbgo.WithDebug(true),
	)

	resp, err := client.Do(context.Background(),
		csbgo.NewRequest(csbgo.MethodPost).
			WithAPI("MyService").
			WithVersion("v1").
			WithQuery("name", "wiseking").
			WithForm("p1", "dog"),
	)
	if err != nil {
		// Non-2xx statuses surface here as *csbgo.StatusError.
		log.Fatalf("call failed: %v", err)
	}

	fmt.Println(resp.ToString())
}

func New

func New(opts ...Option) *Client

New creates a Client with default settings and applies opts in order.

New does not validate the configuration; a request that cannot be built (for example a missing base URL or credentials) fails on the first Do call.

func (*Client) Do

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

Do executes req against CSB and returns the response.

A non-nil error is returned for local failures (invalid request, URL/marshal errors, or an exhausted transport error) and for responses that fail the status check. By default a non-2xx status is such a failure and yields a *StatusError carrying the response (use errors.As to recover it); disable or customize this with WithStatusCheck.

Example

ExampleClient_Do shows a JSON POST body through Client.Do.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/gomodb/csbgo"
)

func main() {
	client := csbgo.New(
		csbgo.WithBaseURL("http://broker.example.com/CSB"),
		csbgo.WithAK("ak"),
		csbgo.WithSK("sk"),
	)

	resp, err := client.Do(context.Background(),
		csbgo.NewRequest(csbgo.MethodPost).
			WithAPI("Echo").
			WithVersion("v1").
			WithJSON(map[string]any{"hello": "world"}),
	)
	if err != nil {
		log.Fatalf("call failed: %v", err)
	}

	var out map[string]any
	if err := resp.ToJSON(&out); err != nil {
		log.Fatalf("decode failed: %v", err)
	}

	fmt.Printf("%v\n", out)
}

func (*Client) DoAs added in v0.5.0

func (c *Client) DoAs[T any](ctx context.Context, req *Request) (T, error)

DoAs performs Do and returns the response body decoded into a value of type T. The status check still applies: a rejected status is returned as a *StatusError and the returned T is the zero value. Deserialization failures surface as an *Error.

user, err := client.DoAs[User](ctx, req)
Example

ExampleClient_DoAs shows the generic, typed one-step call.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/gomodb/csbgo"
)

func main() {
	client := csbgo.New(
		csbgo.WithBaseURL("http://broker.example.com/CSB"),
		csbgo.WithAK("ak"),
		csbgo.WithSK("sk"),
	)

	type User struct {
		Name string `json:"name"`
	}

	user, err := client.DoAs[User](context.Background(),
		csbgo.NewRequest(csbgo.MethodGet).
			WithAPI("UserService").
			WithVersion("v1"))
	if err != nil {
		log.Fatalf("call failed: %v", err)
	}

	fmt.Println(user.Name)
}

type Code added in v0.5.1

type Code int

Code is a CSB error code.

CSB reports a failure by using an escape code of the consumer protocol (HTTP uses 500) and embedding the real code in the description as "[CSB Error Code] CSB Error Message". When the failure happened at the service provider, the CSB escape code CodeServiceServerError (800) is used and the provider's own code follows: "[800][Provider Code] Provider Message".

Those fields are parsed into Error.Code, Error.ProviderCode and Error.Message and surfaced through the *StatusError returned by Client.Do.

const (
	CodeSuccess Code = 200

	CodePlatformError              Code = 500
	CodeAccessDenied               Code = 501
	CodeSignatureVerificationError Code = 502
	CodeServiceNotRegistered       Code = 503
	CodeAPINameNotFound            Code = 504
	CodeAccessKeyNotFound          Code = 505
	CodeSignatureNotFound          Code = 506
	CodeRequiredParameterMissing   Code = 507
	CodeSecureChannelRequired      Code = 508
	CodeTimestampNotFound          Code = 509
	CodeTimeExpired                Code = 510
	CodeInvokeTimeout              Code = 511
	CodeWriteChannelError          Code = 512
	CodeConnectionBroken           Code = 513
	CodeHSFAddressNotFound         Code = 514
	CodeHSFProcessError            Code = 515
	CodeHOHProcessError            Code = 516
	CodeJSONToHSFProcessError      Code = 517
	CodeServiceMetadataNull        Code = 518
	CodeBlackListDenied            Code = 519
	CodeServiceMetadataNotFound    Code = 520
	CodeIPNotInWhiteList           Code = 521
	CodeProtocolNotOpen            Code = 522
	CodeStrictAccessKeyWhiteList   Code = 523
	CodeAccessLimited              Code = 524

	// CodeServiceServerError is the CSB escape code for a failure at the
	// service provider; ProviderCode then carries the provider's own code.
	CodeServiceServerError     Code = 800
	CodeConnectToProviderError Code = 801
	CodeServiceOffline         Code = 802
	CodeServiceStopped         Code = 803

	// CodeHSFEscape is the escape code of the HSF consumer protocol.
	CodeHSFEscape Code = 99

	// CodeUnknown is used by CSB when it cannot classify the failure.
	CodeUnknown Code = 900

	CodeBadSOAPRequest        Code = 1001
	CodeBadResponse           Code = 1002
	CodeBadHSFSubscribeInfo   Code = 1003
	CodeHSFInvokeException    Code = 1004
	CodeBadInputSOAPParsing   Code = 1005
	CodeBadOutputSOAPParsing  Code = 1006
	CodeBadInvokeRESTProvider Code = 1007
	CodeBadJSONToWSRequest    Code = 1008
	CodeJSONToWSProcessError  Code = 1009
	CodeResultFilterFailed    Code = 10001
)

CSB error codes.

const EscapeCodeHTTP Code = CodePlatformError

EscapeCodeHTTP is the escape code of the HTTP consumer protocol: a CSB stage-2 or stage-3 failure arrives as this HTTP status, with the real code in the body.

func (Code) Known added in v0.5.1

func (c Code) Known() bool

Known reports whether c is a documented CSB error code.

func (Code) String added in v0.5.1

func (c Code) String() string

String returns the CSB description of the code, or "csb code N" when the code is not one of the documented ones.

type Error

type Error struct {
	// Err is the underlying error that triggered the failure (may be nil).
	Err error
	// Request describes the request that was sent. It is nil for failures
	// detected before a request could be built (validation, base URL, ...).
	Request *RequestInfo
	// Response is the received response, or nil when none was received (for
	// example a transport error).
	Response *Response
	// Message is the CSB error message with any "[code] " prefixes stripped, or
	// a local description of the failure.
	Message string
	// RequestID correlates this call with the CSB/console log, when present.
	RequestID string
	// Code is the CSB error code; it is 0 when none was recognised.
	Code Code
	// ProviderCode is the service provider's own error code, reported verbatim
	// by CSB for a stage-3 failure (Code == CodeServiceServerError). Its meaning
	// depends on the provider protocol and is not interpreted here.
	ProviderCode int
	// StatusCode is the HTTP status code; it is 0 when no response was received.
	StatusCode int
}

Error describes a CSB call failure and carries what is needed to report or debug it: the parsed CSB error fields, the request that was sent, and the response that came back when one did.

For local failures (validation, transport, encoding) it wraps the cause in Err. For failures reported by the broker it is reachable with errors.As through the returned *StatusError.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) ProviderError added in v0.5.1

func (e *Error) ProviderError() bool

ProviderError reports whether the failure happened at the service provider (CSB escape code 800) rather than inside CSB itself.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error so errors.Is/errors.As work as expected.

type JitterStrategy added in v0.5.0

type JitterStrategy int

JitterStrategy controls how randomness is applied to a computed backoff delay. Jitter spreads retries out so that many clients do not retry at the same instant (the "thundering herd" problem).

const (
	// NoJitter uses the raw exponential backoff.
	NoJitter JitterStrategy = iota
	// FullJitter draws the wait uniformly from [0, cap). This is the default.
	FullJitter
	// EqualJitter keeps at least half the cap: cap/2 + rand[0, cap/2).
	EqualJitter
)

type Logger

type Logger interface {
	Debug(msg string, args ...any)
}

Logger is the debug-logging sink used by Client when debug mode is enabled. It is the subset of *slog.Logger that this package uses, so any *slog.Logger satisfies it.

type Option

type Option func(*Client)

Option customizes a Client. Options are applied in order by New.

func WithAK

func WithAK(ak string) Option

WithAK sets the default access key for requests that do not set their own.

func WithAPI

func WithAPI(api string) Option

WithAPI sets a default API name for requests that do not set their own.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL sets the CSB endpoint the client calls. It is required: a CSB client targets a single endpoint, and every request is sent to this URL's host/path. End it with "/" if the path should behave as a directory.

func WithDebug

func WithDebug(debug bool) Option

WithDebug enables debug logging via the configured Logger.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets a custom *http.Client. Use it for advanced transport needs (proxy, TLS config, keep-alive tuning, custom RoundTripper). Do not call WithTimeout on a client you supplied here in a way that conflicts with its own Timeout. Pass nil to restore the default client.

func WithJitter added in v0.5.0

func WithJitter(s JitterStrategy) Option

WithJitter sets the jitter strategy applied to the computed backoff. It defaults to FullJitter.

func WithLogger

func WithLogger(l Logger) Option

WithLogger sets the debug log sink. It defaults to a slog text logger writing to stderr at debug level. Pass any *slog.Logger (e.g. slog.Default()), or a type implementing this package's narrow Logger interface. Pass nil to restore the default sink.

func WithMaxRetryDelay added in v0.5.1

func WithMaxRetryDelay(max time.Duration) Option

WithMaxRetryDelay caps any single retry wait. The default is 30s. It also bounds the wait requested by a Retry-After header.

func WithOnRetry added in v0.5.0

func WithOnRetry(fn func(RetryInfo)) Option

WithOnRetry sets a callback invoked just before each retry wait, for logging or metrics.

func WithRetries

func WithRetries(n int) Option

WithRetries sets how many times a call is retried on transport errors and retryable status codes (5xx and 429). A value <= 0 disables retries (the default). It can be overridden per request with Request.WithRetries.

func WithRetryBackoff added in v0.5.0

func WithRetryBackoff(base time.Duration) Option

WithRetryBackoff sets the initial retry backoff; it doubles each attempt. The default is 100ms. Use WithMaxRetryDelay to bound a single wait.

func WithRetryDelay added in v0.5.0

func WithRetryDelay(fn func(attempt int, err error) time.Duration) Option

WithRetryDelay replaces the built-in backoff (and jitter) with a custom schedule. It receives the 1-based retry attempt and the triggering error. A Retry-After header still takes precedence, and the result is capped at the configured maximum delay.

func WithRetryIf added in v0.5.0

func WithRetryIf(fn func(resp *Response, err error) bool) Option

WithRetryIf sets a predicate that decides, per outcome, whether to retry. Exactly one of resp/err is non-nil: err is set for transport failures, resp for a received response. Context cancellation and deadline are never retried, whatever the predicate returns.

func WithSK

func WithSK(sk string) Option

WithSK sets the default secret key for requests that do not set their own.

func WithStatusCheck

func WithStatusCheck(f func(int) bool) Option

WithStatusCheck sets how response status codes are classified. It defaults to accepting 2xx only. Pass a checker such as AcceptStatus (specific codes) or AcceptAnyStatus (accept everything), and pass nil to restore the default 2xx-only check.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the total request timeout on the client's *http.Client. Options apply in order, so call it after WithHTTPClient if you want it to override a custom client's timeout.

func WithTransport

func WithTransport(rt http.RoundTripper) Option

WithTransport sets the http.RoundTripper used by the client's http.Client. Use RoundTripFunc to adapt a plain function, or wrap http.DefaultTransport for proxy/TLS/logging needs.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets the User-Agent header value.

func WithVersion

func WithVersion(v string) Option

WithVersion sets a default API version for requests that do not set their own.

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request describes a single CSB HTTP invocation. Use NewRequest to create it and the With* methods to build it up fluently.

Query and Form values all feed into the CSB signature (the broker signs the union of URL query params and form params), so do not pass a parameter in a different way than the service contract expects. Use the With*Values setters (or repeated keys in the base URL) when a service contract takes a parameter more than once.

func NewRequest

func NewRequest(method string) *Request

NewRequest creates a request for the given method. method is case-insensitive; CSB services are typically called with "GET" or "POST" (the only methods the broker accepts).

The request URL is the client's base URL (set with WithBaseURL), since a CSB client targets a single endpoint. Use WithHost/WithPath to refine it per request when needed.

func (*Request) Clone

func (r *Request) Clone() *Request

Clone returns a copy of the request that is safe to mutate independently. It is useful for holding a reusable "endpoint template" and deriving per-call variants without disturbing the original.

Example

ExampleRequest_Clone shows deriving per-call requests from an endpoint template without mutating the original.

package main

import (
	"github.com/gomodb/csbgo"
)

func main() {
	base := csbgo.NewRequest(csbgo.MethodGet).
		WithAPI("MyService").
		WithVersion("v1")

	user := base.Clone().WithPath("users/").WithPath("1001")
	orders := base.Clone().WithPath("orders/").WithQueryInt("page", 2)

	_ = user
	_ = orders
	// Pass user / orders to client.Do(ctx, ...).
}

func (*Request) WithAK

func (r *Request) WithAK(ak string) *Request

WithAK overrides the access key for this request only.

func (*Request) WithAPI

func (r *Request) WithAPI(api string) *Request

WithAPI sets the CSB API (service) name.

func (*Request) WithBody

func (r *Request) WithBody(contentType string, body []byte) *Request

WithBody sets a raw request body with an explicit content type. For POST requests without an explicit body, form parameters are sent as application/x-www-form-urlencoded automatically. Only POST requests may carry an explicit body; Client.Do rejects it otherwise.

func (*Request) WithForm

func (r *Request) WithForm(key, value string) *Request

WithForm replaces the form values of key with the single value value. Form parameters are sent as the application/x-www-form-urlencoded request body of a form-POST, or appended to the URL query otherwise (see README).

func (*Request) WithFormValues added in v0.3.0

func (r *Request) WithFormValues(key string, values ...string) *Request

WithFormValues replaces the form values of key with the given list, allowing a repeated form parameter to carry several occurrences.

func (*Request) WithForms

func (r *Request) WithForms(pairs map[string]string) *Request

WithForms adds several form parameters, each with a single value.

func (*Request) WithHeader

func (r *Request) WithHeader(key, value string) *Request

WithHeader adds a single HTTP header.

func (*Request) WithHeaders

func (r *Request) WithHeaders(h map[string]string) *Request

WithHeaders adds multiple HTTP headers.

func (*Request) WithHost added in v0.5.1

func (r *Request) WithHost(host string) *Request

WithHost overrides the host of the request URL.

func (*Request) WithJSON

func (r *Request) WithJSON(v any) *Request

WithJSON marshals v to JSON at call time and sets content type to application/json. Marshal errors are surfaced by Client.Do. Only POST requests may carry an explicit body.

func (*Request) WithJitter added in v0.5.1

func (r *Request) WithJitter(s JitterStrategy) *Request

WithJitter overrides the jitter strategy for this request only.

func (*Request) WithMaxRetryDelay added in v0.5.1

func (r *Request) WithMaxRetryDelay(max time.Duration) *Request

WithMaxRetryDelay overrides the cap on a single retry wait for this request.

func (*Request) WithMethod

func (r *Request) WithMethod(m string) *Request

WithMethod overrides the HTTP method used for this request. Only GET and POST are supported; Client.Do rejects anything else.

func (*Request) WithOnRetry added in v0.5.1

func (r *Request) WithOnRetry(fn func(RetryInfo)) *Request

WithOnRetry overrides the per-retry callback for this request only. Pass nil to inherit the client default again.

func (*Request) WithPath added in v0.5.1

func (r *Request) WithPath(path string) *Request

WithPath joins a path segment onto the request URL per RFC 3986. A leading "/" overrides the existing path; "./" and "../" are resolved into their absolute form when the URL is built.

func (*Request) WithPathf added in v0.5.1

func (r *Request) WithPathf(format string, a ...any) *Request

WithPathf calls WithPath with fmt.Sprintf. Do not pass user input through %s.

func (*Request) WithQueries

func (r *Request) WithQueries(pairs map[string]string) *Request

WithQueries adds several URL query parameters, each with a single value.

func (*Request) WithQuery

func (r *Request) WithQuery(key, value string) *Request

WithQuery replaces the URL query values of key with the single value value (calling it twice with the same key overrides the earlier value).

func (*Request) WithQueryInt

func (r *Request) WithQueryInt(key string, value int) *Request

WithQueryInt adds a URL query parameter whose value is an integer.

func (*Request) WithQueryValues added in v0.3.0

func (r *Request) WithQueryValues(key string, values ...string) *Request

WithQueryValues replaces the URL query values of key with the given list, so a service contract that accepts the parameter more than once can send several occurrences.

func (*Request) WithRetries added in v0.5.0

func (r *Request) WithRetries(n int) *Request

WithRetries overrides the retry count for this request only. A value <= 0 disables retries for this request, regardless of the client default.

func (*Request) WithRetryBackoff added in v0.5.1

func (r *Request) WithRetryBackoff(base time.Duration) *Request

WithRetryBackoff overrides the initial retry backoff for this request only.

func (*Request) WithRetryDelay added in v0.5.1

func (r *Request) WithRetryDelay(fn func(attempt int, err error) time.Duration) *Request

WithRetryDelay overrides the retry delay schedule for this request only. Pass nil to inherit the client default again.

func (*Request) WithRetryIf added in v0.5.0

func (r *Request) WithRetryIf(fn func(resp *Response, err error) bool) *Request

WithRetryIf overrides the retry predicate for this request only. Context cancellation and deadline are never retried, whatever the predicate returns. Pass nil to inherit the client default again.

func (*Request) WithSK

func (r *Request) WithSK(sk string) *Request

WithSK overrides the secret key for this request only.

func (*Request) WithStatusCheck

func (r *Request) WithStatusCheck(f func(int) bool) *Request

WithStatusCheck overrides the status check for this request only. Pass a checker such as AcceptStatus (specific codes) or AcceptAnyStatus (disable checking). Pass nil to inherit the client default again.

func (*Request) WithVersion

func (r *Request) WithVersion(v string) *Request

WithVersion sets the API version.

type RequestInfo added in v0.5.1

type RequestInfo struct {
	// Header holds the headers as sent. The secret key and the signature are
	// masked; other headers, including the access key, are kept verbatim.
	Header http.Header
	// Method is the HTTP method used.
	Method string
	// URL is the final request URL, including the encoded query.
	URL string
	// BodyLen is the request body length in bytes (0 when there is no body).
	BodyLen int
}

RequestInfo is a snapshot of the HTTP request the client sent. Credential headers are redacted and the body is represented by its length only, so an error can be logged or reported without leaking secrets.

type Response

type Response struct {
	// Header holds the response HTTP headers (nil if none were returned).
	Header http.Header
	// Body is the raw response body.
	Body []byte
	// StatusCode is the HTTP status code returned by the broker.
	StatusCode int
}

Response holds the result of a CSB invocation.

func (*Response) OK

func (r *Response) OK() bool

OK reports whether the response carries a 2xx status code. It is the literal 2xx check, independent of any WithStatusCheck override.

func (*Response) ToBytes added in v0.2.0

func (r *Response) ToBytes() []byte

ToBytes returns a copy of the raw response body.

func (*Response) ToJSON added in v0.2.0

func (r *Response) ToJSON(v any) error

ToJSON unmarshals the response body into v.

func (*Response) ToString added in v0.2.0

func (r *Response) ToString() string

ToString returns the response body as a string.

type RetryInfo added in v0.5.0

type RetryInfo struct {
	// Err is the transport error that triggered the retry; it is nil when the
	// trigger was a retryable status code.
	Err error
	// Response is the response that triggered the retry when the cause was a
	// retryable status code; it is nil for a transport error.
	Response *Response
	// Attempt is the 1-based number of the retry about to be performed.
	Attempt int
	// Delay is how long the client will wait before that retry.
	Delay time.Duration
}

RetryInfo describes a retry that is about to happen. It is passed to the WithOnRetry callback.

type RoundTripFunc

type RoundTripFunc func(*http.Request) (*http.Response, error)

RoundTripFunc adapts a plain function into an http.RoundTripper, for tests that return canned responses and for middleware that wraps a transport:

c := csbgo.New(
	csbgo.WithAK("ak"), csbgo.WithSK("sk"),
	csbgo.WithTransport(csbgo.RoundTripFunc(func(req *http.Request) (*http.Response, error) {
		// inspect or rewrite req, then delegate
		return http.DefaultTransport.RoundTrip(req)
	})),
)

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type StatusError

type StatusError struct {
	// Err carries the rejected response, the parsed CSB fields, and the request
	// that was sent.
	Err *Error
}

StatusError is returned by Client.Do when the response status is rejected by the status check (a 2xx-only check by default). It exists so callers can single out that case with errors.As; every detail lives on Err, which Unwrap exposes.

func (*StatusError) Error

func (e *StatusError) Error() string

Error implements the error interface.

func (*StatusError) Response

func (e *StatusError) Response() *Response

Response returns the rejected response. It is a shorthand for Err.Response and is nil-safe.

func (*StatusError) Unwrap added in v0.5.1

func (e *StatusError) Unwrap() error

Unwrap exposes the underlying *Error so errors.As/errors.Is reach its request, response and CSB fields.

Jump to

Keyboard shortcuts

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