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 AcceptStatus(codes ...int) func(int) bool
- type Client
- 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 WithOnRetry(fn func(RetryInfo)) Option
- func WithRetries(n int) Option
- func WithRetryBackoff(base, max 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) Host(host string) *Request
- func (r *Request) Path(path string) *Request
- func (r *Request) Pathf(format string, a ...any) *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) WithJSON(v any) *Request
- func (r *Request) WithMethod(m string) *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) 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 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 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 (*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 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)
}
Output:
func (*Client) DoJSON ¶ added in v0.2.0
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)
}
Output:
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.
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.
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.
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 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
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. 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 WithStatusCheck ¶
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 ¶
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 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 ¶
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, ...).
}
Output:
func (*Request) Path ¶
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) 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) WithMethod ¶
WithMethod overrides the HTTP method used for this request.
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.
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.
func (*Request) WithStatusCheck ¶
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 ¶
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.
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 {
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.