Documentation
¶
Overview ¶
Package csbgo implements a minimal, dependency-free client for invoking HTTP services published through Alibaba Cloud CSB (Cloud Service Bus).
Index ¶
- Constants
- func AcceptAnyStatus(int) bool
- func AcceptStatus(codes ...int) func(int) bool
- type Client
- type Code
- type Error
- type JitterStrategy
- type Logger
- type Option
- func WithAK(ak string) Option
- func WithAPI(api string) Option
- func WithBaseURL(u string) Option
- func WithDebug(debug bool) Option
- func WithHTTPClient(c *http.Client) Option
- func WithJitter(s JitterStrategy) Option
- func WithLogger(l Logger) Option
- func WithMaxRetryDelay(max time.Duration) Option
- func WithOnRetry(fn func(RetryInfo)) Option
- func WithRetries(n int) Option
- func WithRetryBackoff(base time.Duration) Option
- func WithRetryDelay(fn func(attempt int, err error) time.Duration) Option
- func WithRetryIf(fn func(resp *Response, err error) bool) Option
- func WithSK(sk string) Option
- func WithStatusCheck(f func(int) bool) Option
- func WithTimeout(d time.Duration) Option
- func WithTransport(rt http.RoundTripper) Option
- func WithUserAgent(ua string) Option
- func WithVersion(v string) Option
- type Request
- func (r *Request) Clone() *Request
- func (r *Request) WithAK(ak string) *Request
- func (r *Request) WithAPI(api string) *Request
- func (r *Request) WithBody(contentType string, body []byte) *Request
- func (r *Request) WithForm(key, value string) *Request
- func (r *Request) WithFormValues(key string, values ...string) *Request
- func (r *Request) WithForms(pairs map[string]string) *Request
- func (r *Request) WithHeader(key, value string) *Request
- func (r *Request) WithHeaders(h map[string]string) *Request
- func (r *Request) WithHost(host string) *Request
- func (r *Request) WithJSON(v any) *Request
- func (r *Request) WithJitter(s JitterStrategy) *Request
- func (r *Request) WithMaxRetryDelay(max time.Duration) *Request
- func (r *Request) WithMethod(m string) *Request
- func (r *Request) WithOnRetry(fn func(RetryInfo)) *Request
- func (r *Request) WithPath(path string) *Request
- func (r *Request) WithPathf(format string, a ...any) *Request
- func (r *Request) WithQueries(pairs map[string]string) *Request
- func (r *Request) WithQuery(key, value string) *Request
- func (r *Request) WithQueryInt(key string, value int) *Request
- func (r *Request) WithQueryValues(key string, values ...string) *Request
- func (r *Request) WithRetries(n int) *Request
- func (r *Request) WithRetryBackoff(base time.Duration) *Request
- func (r *Request) WithRetryDelay(fn func(attempt int, err error) time.Duration) *Request
- func (r *Request) WithRetryIf(fn func(resp *Response, err error) bool) *Request
- func (r *Request) WithSK(sk string) *Request
- func (r *Request) WithStatusCheck(f func(int) bool) *Request
- func (r *Request) WithVersion(v string) *Request
- type RequestInfo
- type Response
- type RetryInfo
- type RoundTripFunc
- type StatusError
Examples ¶
Constants ¶
const ( MethodGet = http.MethodGet MethodPost = http.MethodPost )
Method and content-type convenience constants.
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
AcceptAnyStatus accepts every status code. Pass it to WithStatusCheck to disable status checking.
func AcceptStatus ¶
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())
}
Output:
func New ¶
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 ¶
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)
}
Output:
func (*Client) DoAs ¶ added in v0.5.0
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)
}
Output:
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.
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) ProviderError ¶ added in v0.5.1
ProviderError reports whether the failure happened at the service provider (CSB escape code 800) rather than inside CSB itself.
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 ¶
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 WithBaseURL ¶
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 WithHTTPClient ¶
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 ¶
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
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
WithOnRetry sets a callback invoked just before each retry wait, for logging or metrics.
func WithRetries ¶
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
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
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
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 WithStatusCheck ¶
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 ¶
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 ¶
WithUserAgent sets the User-Agent header value.
func WithVersion ¶
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 ¶
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 ¶
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, ...).
}
Output:
func (*Request) WithBody ¶
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 ¶
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
WithFormValues replaces the form values of key with the given list, allowing a repeated form parameter to carry several occurrences.
func (*Request) WithHeader ¶
WithHeader adds a single HTTP header.
func (*Request) WithHeaders ¶
WithHeaders adds multiple HTTP headers.
func (*Request) WithJSON ¶
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
WithMaxRetryDelay overrides the cap on a single retry wait for this request.
func (*Request) WithMethod ¶
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
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
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
WithPathf calls WithPath with fmt.Sprintf. Do not pass user input through %s.
func (*Request) WithQueries ¶
WithQueries adds several URL query parameters, each with a single value.
func (*Request) WithQuery ¶
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 ¶
WithQueryInt adds a URL query parameter whose value is an integer.
func (*Request) WithQueryValues ¶ added in v0.3.0
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
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
WithRetryBackoff overrides the initial retry backoff for this request only.
func (*Request) WithRetryDelay ¶ added in v0.5.1
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
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) WithStatusCheck ¶
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 ¶
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 ¶
OK reports whether the response carries a 2xx status code. It is the literal 2xx check, independent of any WithStatusCheck override.
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 ¶
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)
})),
)
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.