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) OAuth() *OAuthFlow
- func (client *Client) Request(req *http.Request, out any, opts ...RequestOpt) error
- func (client *Client) String() string
- 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 OAuthFlow
- func (f *OAuthFlow) AuthorizeWithBrowser(ctx context.Context, creds *oauth.OAuthCredentials, listener net.Listener, ...) (*oauth.OAuthCredentials, error)
- func (f *OAuthFlow) AuthorizeWithCode(ctx context.Context, creds *oauth.OAuthCredentials, prompt oauth.PromptFunc, ...) (*oauth.OAuthCredentials, error)
- func (f *OAuthFlow) AuthorizeWithCredentials(ctx context.Context, creds *oauth.OAuthCredentials, scopes ...string) (*oauth.OAuthCredentials, error)
- func (f *OAuthFlow) AuthorizeWithDevice(ctx context.Context, creds *oauth.OAuthCredentials, ...) (*oauth.OAuthCredentials, error)
- func (f *OAuthFlow) Discover(ctx context.Context, endpoint string) (*oauth.OAuthMetadata, error)
- func (f *OAuthFlow) Introspect(ctx context.Context) (*oauth.IntrospectionResponse, error)
- func (f *OAuthFlow) Refresh(ctx context.Context) error
- func (f *OAuthFlow) Register(ctx context.Context, metadata *oauth.OAuthMetadata, clientName string, ...) (*oauth.OAuthCredentials, error)
- func (f *OAuthFlow) Revoke(ctx context.Context) error
- 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 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
func (*Client) OAuth ¶ added in v1.4.0
OAuth returns an OAuthFlow bound to this client. Every method on the returned flow uses the client's own HTTP transport so that proxy, TLS, and timeout settings are consistent across all OAuth and API calls. Pass a context directly to each flow method.
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 OAuthFlow ¶ added in v1.4.0
type OAuthFlow struct {
// contains filtered or unexported fields
}
OAuthFlow is a thin wrapper around the pkg/oauth functions that automatically injects the client's own HTTP transport into every call. Obtain one by calling Client.OAuth(); then call Discover, Register, and the Authorize* methods in sequence, passing your context to each call.
func (*OAuthFlow) AuthorizeWithBrowser ¶ added in v1.4.0
func (f *OAuthFlow) AuthorizeWithBrowser(ctx context.Context, creds *oauth.OAuthCredentials, listener net.Listener, open oauth.OpenFunc, scopes ...string) (*oauth.OAuthCredentials, error)
AuthorizeWithBrowser performs the Authorization Code + PKCE flow via a local loopback HTTP server. listener must already be bound to the redirect port; open is called with the authorization URL and should open it in a browser. On success the credentials are automatically attached to the client.
func (*OAuthFlow) AuthorizeWithCode ¶ added in v1.4.0
func (f *OAuthFlow) AuthorizeWithCode(ctx context.Context, creds *oauth.OAuthCredentials, prompt oauth.PromptFunc, scopes ...string) (*oauth.OAuthCredentials, error)
AuthorizeWithCode performs the Authorization Code + PKCE flow via manual code paste. prompt is called with the authorization URL and must return the code the user copies from the browser. On success the credentials are automatically attached to the client.
func (*OAuthFlow) AuthorizeWithCredentials ¶ added in v1.4.0
func (f *OAuthFlow) AuthorizeWithCredentials(ctx context.Context, creds *oauth.OAuthCredentials, scopes ...string) (*oauth.OAuthCredentials, error)
AuthorizeWithCredentials performs the Client Credentials grant (RFC 6749 §4.4) for machine-to-machine flows where no user interaction is required. On success the credentials are automatically attached to the client.
func (*OAuthFlow) AuthorizeWithDevice ¶ added in v1.4.0
func (f *OAuthFlow) AuthorizeWithDevice(ctx context.Context, creds *oauth.OAuthCredentials, prompt oauth.DevicePromptFunc, scopes ...string) (*oauth.OAuthCredentials, error)
AuthorizeWithDevice performs the Device Authorization Grant (RFC 8628). prompt is called with the user code and verification URI that the user must visit on any browser-capable device. On success the credentials are automatically attached to the client.
func (*OAuthFlow) Discover ¶ added in v1.4.0
Discover fetches OAuth 2.0 / OIDC server metadata from the given endpoint (RFC 8414 / OIDC Discovery). The result can be passed directly to Register or any of the Authorize* methods.
func (*OAuthFlow) Introspect ¶ added in v1.4.0
Introspect queries the server for the active status and metadata of the current access token (RFC 7662). Returns an error if no credentials are attached to the client.
func (*OAuthFlow) Refresh ¶ added in v1.4.0
Refresh exchanges the current credentials' refresh token (or re-runs the client credentials grant) for a fresh access token. It is a no-op when the token is still valid. OnRefresh is called if a new token is obtained. Returns an error if no credentials are attached to the client.
func (*OAuthFlow) Register ¶ added in v1.4.0
func (f *OAuthFlow) Register(ctx context.Context, metadata *oauth.OAuthMetadata, clientName string, redirectURIs ...string) (*oauth.OAuthCredentials, error)
Register performs RFC 7591 dynamic client registration against the server described by metadata. redirectURIs should include every loopback address the browser-based flow might use. Returns credentials carrying the allocated ClientID, ClientSecret, and Metadata.
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 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 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. |
|
oauth
Package oauth provides helpers for OAuth 2.0 authorization flows, token lifecycle management, and server metadata discovery.
|
Package oauth provides helpers for OAuth 2.0 authorization flows, token lifecycle management, and server metadata discovery. |
|
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. |