csbgo

package module
v0.5.0 Latest Latest
Warning

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

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

README

csbgo

Go Reference

一个纯 Go 标准库实现的 CSB(云服务总线)HTTP 服务调用客户端,无任何第三方依赖。

安装

go get github.com/gomodb/csbgo

模块只依赖 Go 标准库,不引入任何第三方依赖。要求 Go 1.27+(使用标准库 encoding/json/v2)。

签名协议

CSB 签名 = base64(HMAC-SHA1(secretKey, canonicalizedParams)),其中 canonicalizedParams 是以下参数的合并集中每一个出现拼成一条 k=v,按 key(同 key 内再按 value)的字典序(字节序)升序拼接得到:

  • URL 中自带的 query 参数(先按表单语义解码:+ 视为空格、%XX 还原)
  • 请求提供的 query 参数
  • 请求提供的 form 参数
  • 协议字段:_api_name、_api_version、_api_timestamp、_api_access_key

重复参数:同名的参数可以出现多次(如 base URL 自带 ?d=1&d=2,或用 WithQueryValues / WithFormValues),每次出现都独立参与签名与发送。

发送侧:合并集统一按标准表单编码重建 URL query(先解码、后编码),签名参数集与线上送达参数集保持一致。

_api_secret_key 与 _api_signature 不会参与签名。签名结果通过 HTTP 头 _api_signature 传递,_api_name / _api_version / _api_timestamp / _api_access_key 也同时作为请求头发送。

快速开始

package main

import (
 "context"
 "log"

 csbgo "github.com/gomodb/csbgo"
)

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

 resp, err := client.Do(context.Background(),
  csbgo.NewRequest(csbgo.MethodPost).
   WithAPI("MyService").
   WithVersion("v1").
   WithQuery("name", "wiseking"). // URL 查询参数(参与签名)
   WithForm("p1", "dog").         // form 参数(参与签名;POST 时作为请求体)
   WithHeader("X-Trace", "abc"),
 )
 if err != nil {
  // 含传输错误与非 2xx 状态错误
  log.Fatalf("call failed: %v", err)
 }
 log.Println(resp.ToString())
}

核心 API

New(opts ...Option) *Client

创建一个可复用的客户端(并发安全)。

Option 作用
WithAK / WithSK 默认的 access key / secret key
WithAPI / WithVersion 默认的 API 名 / 版本
WithBaseURL CSB 端点地址(必填,单个端点)
WithTimeout 总超时时间
WithHTTPClient 传入自定义 *http.Client(代理 / TLS / 连接池等)
WithTransport 传入自定义 http.RoundTripper(可用 RoundTripFunc 适配函数)
WithUserAgent 自定义 User-Agent(默认 csbBroker)
WithDebug 输出调试日志(默认关闭)
WithLogger 自定义日志出口,接受任意 *slog.Logger 或实现 Debug(msg string, args ...any) 的类型(默认 slog text handler 打到 stderr)
WithRetries 重试次数(传输错误、5xx、429;默认 0)
WithRetryBackoff 初始退避与单次等待上限(默认 100ms / 30s)
WithJitter 抖动策略:FullJitter(默认)/ EqualJitter / NoJitter
WithRetryIf 自定义「是否重试」谓词(ctx 取消/超时永不重试)
WithRetryDelay 自定义退避函数,替代内建指数退避
WithOnRetry 每次重试前的回调,用于日志/指标
WithStatusCheck 自定义状态码判定(默认仅接受 2xx,传 nil 关闭检查)
NewRequest(method) *Request

链式构建一次调用:WithAPI / WithVersion / WithQuery / WithQueryInt / WithQueries / WithQueryValues / WithForm / WithForms / WithFormValues / WithHeader / WithHeaders / WithBody / WithJSON,URL 组合用 Host / Path / Pathf,以及按请求覆盖 WithAK / WithSK / WithMethod / WithStatusCheck / WithRetries / WithRetryIf。

WithQuery / WithForm 重复调用同一 key 会替换此前设置的值;需要向同一参数追加多个值(重复参数)时用 WithQueryValues(key, v1, v2, ...) / WithFormValues(key, v1, v2, ...)。WithBody / WithJSON 只支持 POST,对 GET 使用会被 Client.Do 拒绝。

Request 不带 URL:请求地址始终是 Client 的 WithBaseURL 端点。Request 可通过 Clone() 从一个“端点模板”派生单次请求而不影响原请求:

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

r1 := base.Clone().Path("users/").Path("1")      // 读用户
r2 := base.Clone().Path("orders/").WithQueryInt("page", 2)
Client.Do(ctx, req) (*Response, error)

发起调用。

  • error 非空 = 本地失败(参数/URL/序列化/传输重试耗尽)或状态码检查失败。
  • 默认只接受 2xx:非 2xx 返回一个 *StatusError(errors.As 可取出,其 Response 字段携带完整状态码/响应头/响应体),方便读取 CSB 返回的错误详情。
  • 用 WithStatusCheck(nil) 关闭检查(此时任何状态码都不报错),或用 WithStatusCheck(csbgo.AcceptStatus(200, 201, 204)) 自定义。
  • Response 提供 ToString()、ToBytes()、ToJSON(&v)、OK() 便捷方法。
resp, err := client.Do(ctx, req)
if err != nil {
 var se *csbgo.StatusError
 if errors.As(err, &se) {
  log.Printf("broker 返回 %d:%s", se.Response.StatusCode, se.Response.ToString())
 }
 return err
}
var out struct{ Code int `json:"code"` }
_ = resp.ToJSON(&out)
Client.DoJSON(ctx, req, out) (*Response, error)

执行请求并在状态检查通过后把响应体 JSON 反序列化到 out。状态检查失败仍返回 *StatusError(此时 out 不被修改),反序列化失败返回 *StatusError 之外的 *Error。

var out struct{ Code int `json:"code"` }
if _, err := client.DoJSON(ctx, req, &out); err != nil {
    // ...
}
Client.DoAs[T](ctx, req) (T, error)

DoJSON 的泛型版本,直接返回解码后的值,省掉 out 指针参数(利用 Go 1.27 的泛型方法):

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

复用与并发

Client 在 New 之后不可变(Do 只读它),内部 *http.Client 本身并发安全,因此可以初始化一次后设为包级变量,供任意 goroutine / 业务代码复用:

var csbClient = csbgo.New(
    csbgo.WithAK("ak"),
    csbgo.WithSK("sk"),
    csbgo.WithBaseURL("http://broker.example.com/"),
    csbgo.WithTimeout(10*time.Second),
)

func GetUser(ctx context.Context, id int) (*User, error) {
    resp, err := csbClient.Do(ctx,
        csbgo.NewRequest(csbgo.MethodGet).
            WithAPI("UserService").WithVersion("v1").
            Path("users/").Path(strconv.Itoa(id)),
    )
    // ...
}
  • Client 共享、Request 每次新建(或从模板 Clone()):不要把同一个 *Request 边改边并发用,With* 会原地修改它。
  • 需要按租户/服务区分配不同 AK/SK 时,创建多个 Client(每个凭证一个),而不是改全局。

参数发送规则

方法 Query 参数 Form 参数 请求体
GET 追加到 URL 追加到 URL 无
POST(无显式 body) 追加到 URL application/x-www-form-urlencoded 请求体 form 编码
POST + WithJSON 追加到 URL 追加到 URL JSON
POST + WithBody 追加到 URL 追加到 URL 原始字节

带显式请求体(WithJSON / WithBody)的 POST 下,form 参数与 query 参数一样拼接进 URL;仅当 POST 无显式 body 时 form 参数才作为表单请求体发送。GET 不允许携带显式请求体。

无论发送路径如何,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, 5*time.Second), // 指数退避 + 上限
    csbgo.WithJitter(csbgo.FullJitter),                          // 默认即 FullJitter
    csbgo.WithRetryIf(func(resp *csbgo.Response, err error) bool {
        // 只重试网络错误与 5xx/429;证书错误、4xx 不重试。
        if err != nil {
            return true
        }
        return resp.StatusCode >= 500 || resp.StatusCode == 429
    }),
    csbgo.WithOnRetry(func(info csbgo.RetryInfo) {
        slog.Warn("csb retry", "attempt", info.Attempt, "delay", info.Delay)
    }),
)

要点:

  • 重试对象:传输错误、5xx、429;context 取消/超时永不重试(自定义谓词也无法覆盖这一点)。
  • 退避:min(maxDelay, base × 2^(attempt-1)) 后再按 JitterStrategy 抖动。默认 FullJitter(避免惊群),可选 EqualJitter 或 NoJitter。
    • 退避始终受 maxDelay 约束,attempt 很大时也不会溢出。
  • Retry-After:响应带该头(秒数或 HTTP-date 两种格式)时优先采用,但仍受 maxDelay 上限约束。
  • 自定义:WithRetryDelay 可完全替换退避(固定/线性/按错误区分);WithRetryIf 按响应或错误决定是否重试。
  • 按请求覆盖:req.WithRetries(n) / req.WithRetryIf(fn) 只影响该次调用。
  • 可观测:WithOnRetry 回调 + debug 日志 csb: retry(含 attempt/delay/err)。

由于默认开启抖动,等待时长是随机的;需要确定性断言的测试请用 WithJitter(csbgo.NoJitter)。

JSON 处理(encoding/json/v2)

本库的请求序列化(WithJSON)与响应反序列化(ToJSON / DoJSON)使用 Go 1.27 起提供的标准库 encoding/json/v2,零第三方依赖,默认构建即可使用。

与 encoding/json(v1)的差异:

  • 重复键:JSON 对象中出现重复键时,v1 静默保留最后一个值;v2 直接报错。
  • 非法 UTF-8:JSON 字符串中的非法 UTF-8 会被 v2 拒绝。
  • 错误信息文本可能不同(前缀如 jsontext:)。

resp.ToJSON(&out) 遇到「响应体含重复键 / 非法 UTF-8」会返回错误。若 CSB 返回体可能包含重复键,请先自行规范化响应体,或解码到 map[string]json.RawMessage 后按需处理。

日志(log/slog)

调试日志基于标准库 log/slog,零第三方依赖。Logger 只要求一个方法:

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

*slog.Logger 天然满足该接口,直接把现有 logger 传进来即可复用同一套 handler(级别、JSON/Text 格式、字段):

logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))

client := csbgo.New(
    csbgo.WithBaseURL("http://broker.example.com/CSB"),
    csbgo.WithAK("ak"),
    csbgo.WithSK("sk"),
    csbgo.WithDebug(true),   // 总开关
    csbgo.WithLogger(logger),
)
  • WithDebug 是总开关,默认关闭;开启后按 Debug 级别发出,是否落盘再由你的 handler 级别决定。
  • 日志是结构化的:csb: http request(method/url)与 csb: signed request(params/signature)。
  • 签名默认已脱敏(只保留前 4 位),避免 debug 日志泄露可用凭证。
  • 不传 WithLogger 时默认使用 slog text handler 打到 stderr。

运行测试

go test ./...
go test -race ./...

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 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.

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 DoJSON and returns the decoded value directly:

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)
}

func (*Client) DoJSON added in v0.2.0

func (c *Client) DoJSON(ctx context.Context, req *Request, out any) (*Response, error)

DoJSON performs Do and, on success, decodes the response body as JSON into out. The status check still applies: a rejected status is returned as a *StatusError and out is left untouched. Deserialization errors surface as an *Error wrapping the encoding/json error.

Example

ExampleClient_DoJSON shows a one-step request + JSON decode via Client.DoJSON.

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"),
	)

	var out map[string]any

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

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

type Error

type Error struct {
	// Err is the underlying error that triggered the failure (may be nil).
	Err error
	// Message is CSB's detailed error message, when the broker returned one.
	Message string
	// RequestID correlates this call with the CSB/console log, when present.
	RequestID string
	// StatusCode is the HTTP status code; it is 0 when no response was received.
	StatusCode int
}

Error is the error type returned by this package. It carries CSB's own error fields (when present), the HTTP status code, and any underlying error so callers can introspect failures without string matching.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

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.

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.

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, max time.Duration) Option

WithRetryBackoff sets the initial backoff and the cap on any single wait. The delay doubles each attempt from base up to max. Defaults are 100ms and 30s.

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. err is non-nil for transport errors; resp is non-nil for responses (including the case where err is nil). 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 nil to return every response with a nil error, or a checker such as AcceptStatus to accept specific codes.

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 request URL is the client's base URL (set with WithBaseURL), since a CSB client targets a single endpoint. Use Path/Host 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().Path("users/").Path("1001")
	orders := base.Clone().Path("orders/").WithQueryInt("page", 2)

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

func (*Request) Host

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

Host overrides the host of the request URL.

func (*Request) Path

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

Path 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) Pathf

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

Pathf calls Path with fmt.Sprintf. Do not pass user input through %s.

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) 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) WithMethod

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

WithMethod overrides the HTTP method used for this request.

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.

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.

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 nil to disable status checking for this request entirely (regardless of the client default), or a function such as AcceptStatus to accept specific codes.

func (*Request) WithVersion

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

WithVersion sets the API version.

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.

func (*Response) ToBytes added in v0.2.0

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

ToBytes returns 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 {
	Response *Response
}

StatusError is returned by Client.Do for responses whose status code is not accepted by the client's status check (a 2xx-only check by default). It wraps the full *Response so callers can still inspect headers and body (e.g. to decode a CSB error payload) via errors.As.

func (*StatusError) Error

func (e *StatusError) Error() string

Error implements the error interface. The body is truncated to keep error strings from becoming huge.

Jump to

Keyboard shortcuts

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