Documentation
¶
Index ¶
- Constants
- Variables
- func ClearCaches(ctx context.Context) error
- func CreateCacheKey(req *http.Request, opts ...CacheOption) (string, error)
- func GrpcCodeFromHTTPStatus(httpStatus int) codes.Code
- func IsJSONContentType(contentType string) bool
- func IsXMLContentType(contentType string) bool
- func NewClient(ctx context.Context, options ...Option) (*http.Client, error)
- func NewHttpCache(ctx context.Context, config *CacheConfig) (icache, error)
- func RedactSensitiveHeaders(h http.Header) http.Header
- func WrapErrors(preferredCode codes.Code, statusMsg string, errs ...error) error
- func WrapErrorsWithRateLimitInfo(preferredCode codes.Code, resp *http.Response, errs ...error) error
- type AuthCredentials
- type BaseHttpClient
- type BasicAuth
- type BearerAuth
- type CacheBackend
- type CacheConfig
- type CacheOption
- type CacheRow
- type CacheStats
- type ContextKey
- type CreateJWTConfig
- type DBCache
- type DoOption
- func WithAlwaysJSONResponse(response any) DoOption
- func WithAlwaysXMLResponse(response any) DoOption
- func WithErrorResponse(resource ErrorResponse) DoOption
- func WithGenericResponse(response *map[string]any) DoOption
- func WithJSONResponse(response any) DoOption
- func WithNextLinkPagination(bag *pagination.Bag, config *NextLinkConfig) DoOption
- func WithPaginationData(response PaginatedResponse) DoOption
- func WithRatelimitData(resource *v2.RateLimitDescription) DoOption
- func WithResponse(response any) DoOption
- func WithXMLResponse(response any) DoOption
- type ErrorResponse
- type GoCache
- func (g *GoCache) Clear(ctx context.Context) error
- func (g *GoCache) Delete(key string) error
- func (g *GoCache) Get(req *http.Request, opts ...CacheOption) (*http.Response, error)
- func (g *GoCache) Has(key string) bool
- func (g *GoCache) Set(req *http.Request, value *http.Response, opts ...CacheOption) error
- func (g *GoCache) Stats(ctx context.Context) CacheStats
- type HttpClient
- type NextLinkConfig
- type NoAuth
- type NoopCache
- type OAuth2ClientCredentials
- type OAuth2JWT
- type OAuth2RefreshToken
- type Option
- type PaginatedResponse
- type RequestOption
- func WithAccept(value string) RequestOption
- func WithAcceptJSONHeader() RequestOption
- func WithAcceptVndJSONHeader() RequestOption
- func WithAcceptXMLHeader() RequestOption
- func WithBearerToken(token string) RequestOption
- func WithBody(body []byte) RequestOption
- func WithContentType(ctype string) RequestOption
- func WithContentTypeFormHeader() RequestOption
- func WithContentTypeJSONHeader() RequestOption
- func WithContentTypeVndHeader() RequestOption
- func WithContentTypeXMLHeader() RequestOption
- func WithFormBody(body string) RequestOption
- func WithHeader(key, value string) RequestOption
- func WithJSONBody(body any) RequestOption
- func WithNoCache() RequestOption
- func WithXMLBody(body any) RequestOption
- type Transport
- type WrapperOption
- type WrapperResponse
Constants ¶
const (
ContentType = "Content-Type"
)
Variables ¶
var ContextHTTPTimeoutKey = contextKeyType{}
ContextHTTPTimeoutKey is the context key used to pass the HTTP timeout duration from the CLI configuration to uhttp.NewClient.
var ErrMissingPaginationData = errors.New("uhttp: response is missing pagination data")
ErrMissingPaginationData is the sentinel returned when a successful response decoded fine but carried no pagination data; match it with errors.Is.
Functions ¶
func ClearCaches ¶ added in v0.2.35
func CreateCacheKey ¶ added in v0.2.15
func CreateCacheKey(req *http.Request, opts ...CacheOption) (string, error)
CreateCacheKey generates a cache key based on the request URL, query parameters, and headers.
func GrpcCodeFromHTTPStatus ¶ added in v0.8.12
GrpcCodeFromHTTPStatus maps an HTTP status code to the appropriate gRPC status code.
func IsJSONContentType ¶ added in v0.2.21
func IsXMLContentType ¶ added in v0.2.21
func NewClient ¶
NewClient creates a new HTTP client that uses the given context and options to create a new transport layer.
func NewHttpCache ¶ added in v0.2.46
func NewHttpCache(ctx context.Context, config *CacheConfig) (icache, error)
func RedactSensitiveHeaders ¶ added in v0.5.24
func WrapErrors ¶ added in v0.2.48
Types ¶
type AuthCredentials ¶ added in v0.1.23
type BaseHttpClient ¶ added in v0.1.24
func NewBaseHttpClient ¶ added in v0.1.25
func NewBaseHttpClient(httpClient *http.Client, opts ...WrapperOption) *BaseHttpClient
func NewBaseHttpClientWithContext ¶ added in v0.2.15
func NewBaseHttpClientWithContext(ctx context.Context, httpClient *http.Client, opts ...WrapperOption) (*BaseHttpClient, error)
func (*BaseHttpClient) NewRequest ¶ added in v0.1.24
func (c *BaseHttpClient) NewRequest(ctx context.Context, method string, url *url.URL, options ...RequestOption) (*http.Request, error)
type BasicAuth ¶ added in v0.1.23
func NewBasicAuth ¶ added in v0.1.23
type BearerAuth ¶ added in v0.1.23
type BearerAuth struct {
Token string
}
func NewBearerAuth ¶ added in v0.1.23
func NewBearerAuth(token string) *BearerAuth
type CacheBackend ¶ added in v0.2.46
type CacheBackend string
const ( CacheBackendDB CacheBackend = "db" CacheBackendMemory CacheBackend = "memory" CacheBackendNoop CacheBackend = "noop" )
type CacheConfig ¶ added in v0.2.15
type CacheConfig struct {
LogDebug bool
TTL time.Duration // If 0, cache is disabled
MaxSizeMb uint64 // MB
Backend CacheBackend // If noop, cache is disabled
}
func DefaultCacheConfig ¶ added in v0.2.46
func DefaultCacheConfig() CacheConfig
func NewCacheConfigFromCtx ¶ added in v0.2.46
func NewCacheConfigFromCtx(ctx context.Context) (*CacheConfig, error)
func NewCacheConfigFromEnv ¶ added in v0.2.46
func NewCacheConfigFromEnv() *CacheConfig
func (*CacheConfig) ToString ¶ added in v0.2.46
func (cc *CacheConfig) ToString() string
type CacheOption ¶ added in v0.24.6
type CacheOption interface {
// contains filtered or unexported methods
}
CacheOption configures how CreateCacheKey computes its key, beyond the default set of headers (Accept, Content-Type, Cookie, Range). Kept as an interface so future dimensions (TTL, query-param keying, etc.) can be added without changing CreateCacheKey's or icache's signatures again.
func CacheKeyHeaders ¶ added in v0.24.6
func CacheKeyHeaders(headers ...string) CacheOption
CacheKeyHeaders returns a CacheOption that folds the named headers into the cache key computed by CreateCacheKey (and by GoCache/DBCache's Get/Set), beyond the default set (Accept, Content-Type, Cookie, Range). The value folded in is always read from req.Header at key-computation time, so the key can never describe a value other than the one actually present on the request. Named headers must therefore be set on the request before it reaches the cache lookup; a header only added by a transport-level RoundTripper or a cookie jar after that point is not seen.
type CacheStats ¶ added in v0.2.46
type ContextKey ¶ added in v0.2.15
type ContextKey struct{}
type CreateJWTConfig ¶ added in v0.1.23
type DBCache ¶ added in v0.2.46
type DBCache struct {
// contains filtered or unexported fields
}
func NewDBCache ¶ added in v0.2.46
func NewDBCache(ctx context.Context, cfg CacheConfig) (*DBCache, error)
TODO (ggreer): obey c1z-temp-dir CLI arg or environment variable
type DoOption ¶ added in v0.1.24
type DoOption func(resp *WrapperResponse) error
func WithAlwaysJSONResponse ¶ added in v0.2.48
Ignore content type header and always try to parse the response as JSON.
func WithAlwaysXMLResponse ¶ added in v0.3.27
Ignore content type header and always try to parse the response as XML.
A *map[string]any target is decoded through the generic xmlMap decoder, since encoding/xml cannot unmarshal into a map and would fail for every input. Any other target keeps going straight to xml.Unmarshal, so callers passing a typed struct are unaffected.
func WithErrorResponse ¶ added in v0.1.27
func WithErrorResponse(resource ErrorResponse) DoOption
func WithGenericResponse ¶ added in v0.3.9
Handle anything that can be marshaled into JSON or XML. If the response is a list, its values will be put into the "items" field. If the response is a single value (int, string, bool, etc), it will be put into the "value" field. A response of `null` results in the "value" field being set to `nil`.
func WithJSONResponse ¶ added in v0.1.24
WithJSONResponse is a wrapper that marshals the returned response body into the provided shape. If the API should return an empty JSON body (i.e. HTTP status code 204 No Content), then pass a `nil` to `response`.
func WithNextLinkPagination ¶ added in v0.2.96
func WithNextLinkPagination(bag *pagination.Bag, config *NextLinkConfig) DoOption
WithNextLinkPagination handles nextlink pagination. The config is optional, and if not provided, the default config will be used.
func WithPaginationData ¶ added in v0.28.0
func WithPaginationData(response PaginatedResponse) DoOption
WithPaginationData decodes the body into response and fails the request if its pagination data is absent, so an API that silently drops its cursor errors instead of ending the sync after one page. response must be a non-nil pointer, since the body is decoded into it.
func WithRatelimitData ¶ added in v0.1.27
func WithRatelimitData(resource *v2.RateLimitDescription) DoOption
func WithResponse ¶ added in v0.1.32
func WithXMLResponse ¶ added in v0.1.28
type ErrorResponse ¶ added in v0.1.27
type ErrorResponse interface {
Message() string
}
type GoCache ¶ added in v0.2.15
type GoCache struct {
// contains filtered or unexported fields
}
func NewGoCache ¶ added in v0.2.15
func NewGoCache(ctx context.Context, cfg CacheConfig) (*GoCache, error)
type HttpClient ¶ added in v0.1.24
type NextLinkConfig ¶ added in v0.2.96
type NextLinkConfig struct {
Header string `json:"header,omitempty"` // HTTP header containing the next link. Defaults to "link".
Rel string `json:"rel,omitempty"` // The rel value to look for in the link header. Defaults to "next".
ResourceTypeID string `json:"resource_type_id,omitempty"`
ResourceID string `json:"resource_id,omitempty"`
}
type NoopCache ¶ added in v0.2.46
type NoopCache struct {
// contains filtered or unexported fields
}
func NewNoopCache ¶ added in v0.2.46
type OAuth2ClientCredentials ¶ added in v0.1.23
type OAuth2ClientCredentials struct {
// contains filtered or unexported fields
}
func NewOAuth2ClientCredentials ¶ added in v0.1.23
func NewOAuth2ClientCredentials(clientId, clientSecret string, tokenURL *url.URL, scopes []string) *OAuth2ClientCredentials
type OAuth2JWT ¶ added in v0.1.23
type OAuth2JWT struct {
Credentials []byte
Scopes []string
CreateJWTConfig CreateJWTConfig
}
func NewOAuth2JWT ¶ added in v0.1.23
func NewOAuth2JWT(credentials []byte, scopes []string, createfn CreateJWTConfig) *OAuth2JWT
type OAuth2RefreshToken ¶ added in v0.1.34
type OAuth2RefreshToken struct {
// contains filtered or unexported fields
}
func NewOAuth2RefreshToken ¶ added in v0.1.34
func NewOAuth2RefreshToken(clientID, clientSecret, redirectURI, tokenURL, accessToken, refreshToken string, scopes []string) *OAuth2RefreshToken
type Option ¶
type Option interface {
Apply(*Transport)
}
func WithLogger ¶
WithLogger sets a logger options to the transport layer.
func WithTLSClientConfig ¶
WithTLSClientConfig returns an Option that sets the TLS client configuration. `tlsConfig` is a structure that is used to configure a TLS client or server.
func WithTimeout ¶ added in v0.7.17
WithTimeout sets the HTTP client timeout. Defaults to 300s (5 minutes) if not specified.
func WithUserAgent ¶
WithUserAgent sets a user agent option to the transport layer.
type PaginatedResponse ¶ added in v0.28.0
type PaginatedResponse interface {
HasPaginationData() bool
}
PaginatedResponse is implemented by response types that can report whether the API returned the pagination data the caller needs to fetch the next page.
type RequestOption ¶ added in v0.1.24
type RequestOption func() (io.ReadWriter, map[string]string, error)
func WithAccept ¶ added in v0.2.13
func WithAccept(value string) RequestOption
func WithAcceptJSONHeader ¶ added in v0.1.24
func WithAcceptJSONHeader() RequestOption
func WithAcceptVndJSONHeader ¶ added in v0.2.13
func WithAcceptVndJSONHeader() RequestOption
func WithAcceptXMLHeader ¶ added in v0.1.28
func WithAcceptXMLHeader() RequestOption
func WithBearerToken ¶ added in v0.2.59
func WithBearerToken(token string) RequestOption
func WithBody ¶ added in v0.2.97
func WithBody(body []byte) RequestOption
func WithContentType ¶ added in v0.2.13
func WithContentType(ctype string) RequestOption
func WithContentTypeFormHeader ¶ added in v0.2.13
func WithContentTypeFormHeader() RequestOption
func WithContentTypeJSONHeader ¶ added in v0.1.24
func WithContentTypeJSONHeader() RequestOption
func WithContentTypeVndHeader ¶ added in v0.2.13
func WithContentTypeVndHeader() RequestOption
func WithContentTypeXMLHeader ¶ added in v0.2.87
func WithContentTypeXMLHeader() RequestOption
func WithFormBody ¶ added in v0.2.13
func WithFormBody(body string) RequestOption
func WithHeader ¶ added in v0.1.33
func WithHeader(key, value string) RequestOption
func WithJSONBody ¶ added in v0.1.24
func WithJSONBody(body any) RequestOption
func WithNoCache ¶ added in v0.3.37
func WithNoCache() RequestOption
func WithXMLBody ¶ added in v0.2.87
func WithXMLBody(body any) RequestOption
type Transport ¶
type Transport struct {
// contains filtered or unexported fields
}
func NewTransport ¶
NewTransport creates a new Transport, applies the options, and then cycles the transport.
type WrapperOption ¶ added in v0.2.38
type WrapperOption interface {
Apply(*BaseHttpClient)
}
func WithCacheKeyHeaders ¶ added in v0.24.6
func WithCacheKeyHeaders(headers ...string) WrapperOption
WithCacheKeyHeaders returns a WrapperOption that additionally folds the named headers into the HTTP response cache key for every request this client makes, on top of the default set (Accept, Content-Type, Cookie, Range). Use this when requests through this client vary by a header the cache wouldn't otherwise key on -- e.g. a per-call Authorization token or a tenant/version header -- so requests that only differ in that header don't collide in the cache. The value folded in is always read from req.Header at request time, so the key can never describe a value other than the one actually sent.
Named headers must be set on the request before it reaches Do; a header only added later by a transport-level RoundTripper or a cookie jar is not seen by the cache lookup and will not be reflected in the key.
func WithMetricsHandler ¶ added in v0.7.19
func WithMetricsHandler(handler metrics.Handler) WrapperOption
WithMetricsHandler returns a WrapperOption that sets the metrics handler for the http client. When set, cache hits and misses will be recorded as metrics.
func WithRateLimiter ¶ added in v0.2.38
func WithRateLimiter(rate int, per time.Duration) WrapperOption
WithRateLimiter returns a WrapperOption that sets the rate limiter for the http client. `rate` is the number of requests allowed per `per` duration. `per` is the duration in which the rate limit is enforced. Example: WithRateLimiter(10, time.Second) will allow 10 requests per second.