Documentation
¶
Overview ¶
Implements a generic REST API client which can be used for creating gateway-specific clients. Basic usage:
package main
import (
client "github.com/mutablelogic/go-client"
)
func main() {
// Create a new client
c := client.New(client.OptEndpoint("https://api.example.com/api/v1"))
// Send a GET request, populating a struct with the response
var response struct {
Message string `json:"message"`
}
if err := c.Do(nil, &response, OptPath("test")); err != nil {
// Handle error
}
// Print the response
fmt.Println(response.Message)
}
Index ¶
- Constants
- Variables
- type Client
- func (client *Client) AccessToken() string
- func (client *Client) Do(in Payload, out any, opts ...RequestOpt) error
- func (client *Client) DoWithContext(ctx context.Context, in Payload, out any, opts ...RequestOpt) error
- func (client *Client) Request(req *http.Request, out any, opts ...RequestOpt) error
- type ClientOpt
- func OptEndpoint(value string) ClientOpt
- func OptHeader(key, value string) ClientOpt
- func OptParent(v any) ClientOpt
- func OptRateLimit(value float32) ClientOpt
- func OptReqToken(value Token) ClientOpt
- func OptSkipVerify() ClientOpt
- func OptStrict() ClientOpt
- func OptTimeout(value time.Duration) ClientOpt
- func OptTrace(w io.Writer, verbose bool) ClientOptdeprecated
- func OptTracer(tracer trace.Tracer) ClientOpt
- func OptTransport(fn func(http.RoundTripper) http.RoundTripper) ClientOpt
- func OptUserAgent(value string) ClientOpt
- type JsonStreamCallback
- type Payload
- func NewFormRequest(payload any, accept string) (Payload, error)
- func NewJSONRequest(payload any) (Payload, error)
- func NewJSONRequestEx(method string, payload any, accept string) (Payload, error)
- func NewMultipartRequest(payload any, accept string) (Payload, error)
- func NewRequest() Payload
- func NewRequestEx(method, accept string) Payload
- func NewStreamingMultipartRequest(payload any, accept string) (Payload, error)
- type RequestOpt
- func OptAbsPath(value ...any) RequestOpt
- func OptJsonStreamCallback(fn JsonStreamCallback) RequestOpt
- func OptNoTimeout() RequestOpt
- func OptPath(value ...any) RequestOpt
- func OptQuery(value url.Values) RequestOpt
- func OptReqEndpoint(value string) RequestOpt
- func OptReqHeader(name, value string) RequestOpt
- func OptReqTransport(fn func(http.RoundTripper) http.RoundTripper) RequestOpt
- func OptTextStreamCallback(fn TextStreamCallback) RequestOpt
- func OptToken(value Token) RequestOpt
- type TextStream
- type TextStreamCallback
- type TextStreamEvent
- type Token
- type Unmarshaler
Constants ¶
const ( DefaultTimeout = time.Second * 30 DefaultUserAgent = "github.com/mutablelogic/go-client" PathSeparator = "/" ContentTypeAny = types.ContentTypeAny ContentTypeJson = types.ContentTypeJSON ContentTypeJsonStream = "application/x-ndjson" ContentTypeTextXml = types.ContentTypeTextXml ContentTypeApplicationXml = types.ContentTypeXML ContentTypeTextPlain = types.ContentTypeTextPlain ContentTypeTextHTML = "text/html" ContentTypeBinary = types.ContentTypeBinary )
const (
Bearer = "Bearer"
)
const ( // Mime type for text stream ContentTypeTextStream = types.ContentTypeTextStream )
Variables ¶
var ( MethodGet = NewRequestEx(http.MethodGet, ContentTypeAny) MethodHead = NewRequestEx(http.MethodHead, ContentTypeAny) MethodDelete = NewRequestEx(http.MethodDelete, ContentTypeAny) MethodPut = NewRequestEx(http.MethodPut, ContentTypeAny) )
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
sync.RWMutex
*http.Client
// Parent object for client options
Parent any
// contains filtered or unexported fields
}
func New ¶
New creates a new client with options. OptEndpoint is required as an option to set the endpoint for all requests.
func (*Client) AccessToken ¶ added in v1.4.2
AccessToken returns the current Authorization header value (e.g. "Bearer <token>"), or an empty string when no token is set. Lock-free: reads from an atomic.Value updated by setToken.
func (*Client) Do ¶
func (client *Client) Do(in Payload, out any, opts ...RequestOpt) error
Do a JSON request with a payload, populate an object with the response and return any errors
func (*Client) DoWithContext ¶
func (client *Client) DoWithContext(ctx context.Context, in Payload, out any, opts ...RequestOpt) error
Do a JSON request with a payload, populate an object with the response and return any errors. The context can be used to cancel the request
type ClientOpt ¶
func OptEndpoint ¶
OptEndpoint sets the endpoint for all requests.
func OptParent ¶ added in v1.0.2
OptParent sets the parent client for this client, which is used for setting additional client options in the parent
func OptRateLimit ¶
OptRateLimit sets the limit on number of requests per second and the API will sleep when exceeded. For account tokens this is 1 per second
func OptReqToken ¶
OptReqToken sets a request token for all client requests. This can be overridden by the client for individual requests using OptToken.
func OptSkipVerify ¶
func OptSkipVerify() ClientOpt
OptSkipVerify skips TLS certificate domain verification. It clones the client's own transport rather than mutating http.DefaultTransport.
func OptStrict ¶
func OptStrict() ClientOpt
OptStrict turns on strict content type checking on anything returned from the API
func OptTimeout ¶
OptTimeout sets the timeout on any request. By default, a timeout of 30 seconds is used if OptTimeout is not set
func OptTrace
deprecated
func OptTracer ¶ added in v1.3.0
OptTracer sets the OpenTelemetry tracer for this client. It wraps the underlying HTTP transport so that every HTTP call — including OAuth token refresh and redirect hops — produces a client span. Span names default to "METHOD /path" format.
func OptTransport ¶ added in v1.4.1
func OptTransport(fn func(http.RoundTripper) http.RoundTripper) ClientOpt
OptTransport inserts a transport middleware for all requests made by this client. Multiple calls stack in order; the first call becomes the outermost layer.
func OptUserAgent ¶
OptUserAgent sets the user agent string on each API request It is set to the default if empty string is passed
type JsonStreamCallback ¶ added in v1.0.9
Callback for json stream events, return an error if you want to stop streaming with an error and io.EOF if you want to stop streaming and return success
type Payload ¶
func NewFormRequest ¶
Return a new request with a Form data payload which defaults to POST. The accept parameter is the accepted mime-type of the response.
func NewJSONRequest ¶
Return a new request with a JSON payload which defaults to POST.
func NewJSONRequestEx ¶
Return a new request with a JSON payload with method. The accept parameter is the accepted mime-type of the response.
func NewMultipartRequest ¶
Return a new request with a Multipart Form data payload which defaults to POST. The accept parameter is the accepted mime-type of the response.
func NewRequestEx ¶
Return a new empty request. The accept parameter is the accepted mime-type of the response.
func NewStreamingMultipartRequest ¶ added in v1.3.5
NewStreamingMultipartRequest returns a new request with a Multipart Form data payload that streams the encoded data rather than buffering it in memory. This is useful for large file uploads where buffering would consume too much memory.
The encoding happens in a background goroutine that writes to a pipe while the HTTP client reads from the other end. Encoding errors are propagated via the pipe.
type RequestOpt ¶
type RequestOpt func(*requestOpts) error
func OptAbsPath ¶ added in v1.4.4
func OptAbsPath(value ...any) RequestOpt
OptAbsPath replaces the request path with the provided path segments.
Each argument is treated as exactly one path segment. Leading and trailing slashes on each argument are ignored for path joining, but any slash or dot segment within an argument is preserved as data and percent-encoded in the outbound request.
For example, OptAbsPath("a/b", "c") results in a request target of "/a%2Fb/c", not "/a/b/c".
func OptJsonStreamCallback ¶ added in v1.0.9
func OptJsonStreamCallback(fn JsonStreamCallback) RequestOpt
OptJsonStreamCallback is called for each decoded JSON event
func OptNoTimeout ¶
func OptNoTimeout() RequestOpt
OptNoTimeout disables the timeout for this request, useful for long-running requests. The context can be used instead for cancelling requests
func OptPath ¶
func OptPath(value ...any) RequestOpt
OptPath appends the provided path segments onto the current request path.
Each argument is treated as exactly one path segment. Leading and trailing slashes on each argument are ignored for path joining, but any slash or dot segment within an argument is preserved as data and percent-encoded in the outbound request.
For example, OptPath("a/b", "c") results in a request target of "/a%2Fb/c", not "/a/b/c".
func OptQuery ¶
func OptQuery(value url.Values) RequestOpt
OptQuery adds query parameters to a request
func OptReqEndpoint ¶
func OptReqEndpoint(value string) RequestOpt
OptReqEndpoint modifies the request endpoint for this request only
func OptReqHeader ¶
func OptReqHeader(name, value string) RequestOpt
OptReqHeader sets a header value to the request
func OptReqTransport ¶ added in v1.4.1
func OptReqTransport(fn func(http.RoundTripper) http.RoundTripper) RequestOpt
OptReqTransport inserts a transport middleware for this request only. Multiple calls stack in order; the first call becomes the outermost layer.
func OptTextStreamCallback ¶ added in v1.0.5
func OptTextStreamCallback(fn TextStreamCallback) RequestOpt
OptTextStreamCallback is called for each event in a text stream
func OptToken ¶
func OptToken(value Token) RequestOpt
OptToken adds an authorization header. The header format is "Authorization: Bearer <token>"
type TextStream ¶ added in v1.0.5
type TextStream struct {
// contains filtered or unexported fields
}
Implementation of a text stream, as per https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
After Decode returns, LastEventID and RetryDuration can be used to reconnect:
req.Header.Set("Last-Event-ID", stream.LastEventID())
func NewTextStream ¶ added in v1.0.5
func NewTextStream() *TextStream
Create a new text stream decoder
func (*TextStream) Decode ¶ added in v1.0.5
func (t *TextStream) Decode(r io.Reader, callback TextStreamCallback) error
Decode a text stream. The reader should be a stream of text/event-stream data and the method will return when all the data has been scanned, or the callback returns an error
func (*TextStream) LastEventID ¶ added in v1.4.1
func (t *TextStream) LastEventID() string
LastEventID returns the last event ID received during Decode. Send this as the "Last-Event-ID" request header when reconnecting.
func (*TextStream) RetryDuration ¶ added in v1.4.1
func (t *TextStream) RetryDuration() time.Duration
RetryDuration returns the server-requested reconnect delay from the most recent "retry:" field, or zero if none was received.
type TextStreamCallback ¶ added in v1.0.5
type TextStreamCallback func(TextStreamEvent) error
Callback for text stream events, return an error if you want to return from the Decode method
type TextStreamEvent ¶ added in v1.0.5
type TextStreamEvent struct {
// The event ID to set the EventSource object's last event ID value.
Id string `json:"id,omitempty"`
// A string identifying the type of event described
Event string `json:"event,omitempty"`
// The data field for the message
Data string `json:"data"`
// The reconnection time. If the connection to the server is lost,
// the client should wait for the specified time before attempting to reconnect.
Retry time.Duration `json:"retry,omitempty"`
}
Implementation of a text stream, as per https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format
func (*TextStreamEvent) IsZero ¶ added in v1.0.5
func (t *TextStreamEvent) IsZero() bool
Return true if the event contains no content
func (*TextStreamEvent) Json ¶ added in v1.0.5
func (t *TextStreamEvent) Json(v any) error
Decode the text stream event data as JSON
func (TextStreamEvent) String ¶ added in v1.0.5
func (t TextStreamEvent) String() string
Return the text stream event as a string
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
api
command
|
|
|
pkg
|
|
|
bitwarden
bitwarden implements an API client for bitwarden
|
bitwarden implements an API client for bitwarden |
|
homeassistant
homeassistant implements an API client for Home Assistant API https://developers.home-assistant.io/docs/api/rest/
|
homeassistant implements an API client for Home Assistant API https://developers.home-assistant.io/docs/api/rest/ |
|
ipify
ipify implements a generic API client which parses a JSON response.
|
ipify implements a generic API client which parses a JSON response. |
|
transport
Package transport provides HTTP transport middleware for logging, recording, and other cross-cutting concerns.
|
Package transport provides HTTP transport middleware for logging, recording, and other cross-cutting concerns. |