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 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 WithLogger(l Logger) Option
- func WithRetries(n int) 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) 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) WithSK(sk string) *Request
- func (r *Request) WithStatusCheck(f func(int) bool) *Request
- func (r *Request) WithVersion(v string) *Request
- type Response
- 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 demonstrates the recommended way to configure a Client and invoke 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) 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 Logger ¶
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 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 WithLogger ¶
WithLogger sets the debug log sink. Defaults to a mutex-guarded stderr writer.
func WithRetries ¶
WithRetries sets how many times a call is retried on transport errors and 5xx responses. A value <= 0 disables retries (the default).
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 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 ¶
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, ...) as needed.
}
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.
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.
func (*Request) WithMethod ¶
WithMethod overrides the HTTP method used for this request.
func (*Request) WithQueries ¶
WithQueries adds multiple URL query parameters.
func (*Request) WithQueryInt ¶
WithQueryInt adds a URL query parameter whose value is an integer.
func (*Request) WithStatusCheck ¶
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 ¶
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 RoundTripFunc ¶
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)
})),
)
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.