csbgo

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 18 Imported by: 0

README

csbgo

Go Reference Go Report Card

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

参考了阿里云 csb-sdk/others/golang 的调用实现,保留了其签名协议(HMAC-SHA1 + 字典序规范化),同时修复了原实现中的多处问题(JSON 判断写反、硬编码 ResponseHeaderTimeout、GET 请求携带 body、全局可变默认值等),并提供了更符合 Go 习惯、更易上手的 API。

安装

go get github.com/gomodb/csbgo

模块只依赖 Go 标准库,不引入任何第三方依赖。

签名协议(与原实现的兼容性)

CSB 签名 = base64(HMAC-SHA1(secretKey, canonicalizedParams)),其中 canonicalizedParams 是把以下参数合并后、按 key 的字典序(字节序)升序拼接成 k1=v1&k2=v2&... 得到:

  • URL 中自带的 query 参数(原样,不做转义)
  • 请求提供的 query 参数
  • 请求提供的 form 参数
  • 协议字段:_api_name、_api_version、_api_timestamp、_api_access_key

_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.String())
}

核心 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 输出调试日志(默认打到 stderr)
WithLogger 自定义日志输出(实现 Printf 即可,*log.Logger 天然满足)
WithRetries 传输错误 / 5xx 的重试次数
WithStatusCheck 自定义状态码判定(默认仅接受 2xx,传 nil 关闭检查)
NewRequest(method) *Request

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

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) 关闭检查(恢复为“任何响应都 nil error”),或用 WithStatusCheck(csbgo.AcceptStatus(200, 201, 204)) 自定义。
  • Response 提供 String()、OK()、JSON(&v) 便捷方法。
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.String())
 }
 return err
}
var out struct{ Code int `json:"code"` }
_ = resp.JSON(&out)

复用与并发

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(每个凭证一个),而不是改全局。
  • 已通过 go test -race 验证:单 Client + 请求模板 Clone() 在 64 个并发 goroutine 下无数据竞争。

参数发送规则

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

无论发送路径如何,query 与 form 参数都会一并进入签名,这与 CSB broker 对“参与签名参数”的要求一致。

运行测试

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 demonstrates the recommended way to configure a Client and invoke a CSB-published service.

package main

import (
	"context"
	"fmt"
	"log"

	csbgo "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.String())
}

func New

func New(opts ...Option) *Client

New creates a Client with sensible defaults 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"

	csbgo "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.JSON(&out); err != nil {
		log.Fatalf("decode 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 Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is the debug-logging sink used by Client when debug mode is enabled. It is satisfied by *log.Logger (its Printf method matches) and by any custom implementation, which lets you keep CSB logs in your own logger.

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 WithLogger

func WithLogger(l Logger) Option

WithLogger sets the debug log sink. Defaults to a mutex-guarded stderr writer.

func WithRetries

func WithRetries(n int) Option

WithRetries sets how many times a call is retried on transport errors and 5xx responses. A value <= 0 disables retries (the default).

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

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 (
	csbgo "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, ...) as needed.
}

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.

func (*Request) WithForm

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

WithForm adds a single form (body) parameter.

func (*Request) WithForms

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

WithForms adds multiple form (body) parameters.

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.

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 multiple URL query parameters.

func (*Request) WithQuery

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

WithQuery adds a single URL query parameter.

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) 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 entirely, 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) JSON

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

JSON unmarshals the response body into v.

func (*Response) OK

func (r *Response) OK() bool

OK reports whether the response carries a 2xx status code.

func (*Response) String

func (r *Response) String() string

String returns the response body as a string.

type RoundTripFunc

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

RoundTripFunc adapts a plain function into an http.RoundTripper. It is handy for tests (returning canned responses) and for lightweight middleware:

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