jsonclient

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrIncorrectUsernamePassword = oAuthError{
	ErrorType: "invalid_grant",
	ErrorDesc: "incorrect username or password",
	Code:      http.StatusBadRequest,
}

ErrIncorrectUsernamePassword indicates a bad username or password.

Functions

func GetHTTPStatusCode

func GetHTTPStatusCode(err error) int

GetHTTPStatusCode returns the underlying HTTP status code or -1 if no code could be extracted.

func IsHTTPNotFound added in v1.0.0

func IsHTTPNotFound(err error) bool

IsHTTPNotFound returns true if the error is an HTTP 404 Not Found error

func RegisterLogger added in v0.3.0

func RegisterLogger(l Logger)

RegisterLogger registers a logger to be used by jsonclient. Note this could eventually be extended to allow multiple etc, but right now this just allows us to break the uclog/jsonclient dependency

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client defines a JSON-focused HTTP client TODO: someday this should use a custom http.Client etc

func New

func New(url string, opts ...Option) *Client

New returns a new Client

func (*Client) Apply

func (c *Client) Apply(opts ...Option)

Apply applies options to an existing client (useful for updating a header/cookie/etc on an existing client).

func (*Client) CreateIfNotExists added in v0.6.0

func (c *Client) CreateIfNotExists(ctx context.Context, path string, body, response interface{}, opts ...Option) (bool, uuid.UUID, error)

CreateIfNotExists does a POST and handles the 409 conflict error for the caller

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, path string, body interface{}, opts ...Option) error

Delete makes an HTTP delete using this client

func (*Client) Get

func (c *Client) Get(ctx context.Context, path string, response interface{}, opts ...Option) error

Get makes an HTTP get using this client TODO: need to support query params soon :)

func (*Client) GetBearerToken

func (c *Client) GetBearerToken() (string, error)

GetBearerToken returns the bearer token associated with this client, if one exists, or an error otherwise.

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, path string, body, response interface{}, opts ...Option) error

Patch makes an HTTP patch using this client If response is nil, the response isn't decoded and merely the success or failure is returned

func (*Client) Post

func (c *Client) Post(ctx context.Context, path string, body, response interface{}, opts ...Option) error

Post makes an HTTP post using this client If response is nil, the response isn't decoded and merely the success or failure is returned

func (*Client) Put

func (c *Client) Put(ctx context.Context, path string, body, response interface{}, opts ...Option) error

Put makes an HTTP put using this client If response is nil, the response isn't decoded and merely the success or failure is returned

func (*Client) ValidateBearerTokenHeader

func (c *Client) ValidateBearerTokenHeader() error

ValidateBearerTokenHeader ensures that there is a non-expired bearer token specified directly OR that there's a valid token source to refresh it if not specified or expired.

type DecodeFunc

type DecodeFunc func(ctx context.Context, body io.ReadCloser) error

DecodeFunc is a callback used with the CustomDecoder option to control deserializing the response from an HTTP request. Instead of automatically deserializing into the response object provided to the method (which must be nil instead), this method is invoked.

type Error

type Error struct {
	StatusCode int    `json:"http_status_code"`
	Body       string `json:"response_body"`
}

Error defines a jsonclient error for non-2XX/3XX status codes TODO: decide how to handle 3XX results

func (Error) Code added in v0.3.0

func (e Error) Code() int

Code return the HTTP status code and implements private interface jsonapi.errorWithCode

func (Error) Error

func (e Error) Error() string

Error implements UCError

func (Error) Friendly added in v0.3.0

func (e Error) Friendly() string

Friendly implements UCError

func (Error) FriendlyStructure added in v0.3.0

func (e Error) FriendlyStructure() interface{}

FriendlyStructure implements UCError If the body is JSON, we'll convert it to map[string]interface{} so it gets preserved as something easily unmarshaled in the returned error.

type HeaderFunc

type HeaderFunc func(context.Context) (key string, value string)

HeaderFunc is a callback that's invoked on every request to generate a header This is useful when the header should change per-request based on the context used for that request, eg. a long-lived client that makes requests on behalf of numerous customers with different X-Forwarded-For IPs, etc Note that returning a blank key indicates "no header to add this request"

type Logger added in v0.3.0

type Logger interface {
	Debugf(ctx context.Context, format string, args ...interface{})
}

Logger specifies a minimal interface to allow jsonclient to log errors.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option makes jsonclient extensible

func BypassRouting added in v0.6.4

func BypassRouting() Option

BypassRouting allows you to bypass our internal request rerouting system to test performance

func ClientCredentialsForURL added in v0.7.2

func ClientCredentialsForURL(u string, clientID, clientSecret string, customAudiences []string) (Option, error)

ClientCredentialsForURL can be specified to enable support for RefreshBearerToken automatically refreshing the token if expired.

func ClientCredentialsTokenSource

func ClientCredentialsTokenSource(tokenURL, clientID, clientSecret string, customAudiences []string) Option

ClientCredentialsTokenSource can be specified to enable support for RefreshBearerToken automatically refreshing the token if expired. TODO: deprecate this in favor of the more generic TokenSource option

func Cookie(cookie http.Cookie) Option

Cookie allows you to add cookies to jsonclient requests

func CustomDecoder

func CustomDecoder(f DecodeFunc) Option

CustomDecoder allows the caller to control deserializing the HTTP response. It is most useful when the exact structure of the response is not known ahead of time, and custom logic is required (e.g. for API compatibility).

func Header(k, v string) Option

Header allows you to add arbitrary headers to jsonclient requests

func HeaderAuth added in v0.7.2

func HeaderAuth(auth string) Option

HeaderAuth Adds an Authorization header to the request

func HeaderAuthBearer added in v0.7.2

func HeaderAuthBearer(token string) Option

HeaderAuthBearer Adds an Authorization header w/ a Bearer token to the request

func HeaderHost added in v0.7.2

func HeaderHost(host string) Option

HeaderHost allows you to add a Host header to jsonclient requests

func HeaderUserAgent added in v0.8.3

func HeaderUserAgent(ua string) Option

HeaderUserAgent allows you to add a User-Agent header to jsonclient requests

func ParseOAuthError

func ParseOAuthError() Option

ParseOAuthError allows deserializing & capturing the last call's error into an OAuthError object for deeper inspection. This is richer than a jsonclient.Error but only makes sense on a call that is expected to be OAuth/OIDC compliant.

func PerRequestHeader

func PerRequestHeader(f HeaderFunc) Option

PerRequestHeader allows you to pass in a callback that takes a context and returns a header k,v that will be called on each request and a new header appended to the request

func RetryNetworkErrors added in v0.4.0

func RetryNetworkErrors() Option

RetryNetworkErrors causes the client to retry on underlying network errors TODO: is this a good idea? TODO: should we have a max retry count, backoff, etc config?

func StopLogging

func StopLogging() Option

StopLogging causes the client not to log failures

func TokenSource

func TokenSource(ts oidc.TokenSource) Option

TokenSource takes an arbitrary token source

func UnmarshalOnError

func UnmarshalOnError() Option

UnmarshalOnError causes the response struct to be deserialized if a HTTP 400+ code is returned. The default behavior is to not deserialize and to return an error.

type RequestRouter added in v0.6.4

type RequestRouter interface {
	Reroute(context.Context, *http.Request)
}

RequestRouter allows jsonclient to internally reroute requests to specific hosts / clusters / pods

var Router RequestRouter

Router is jsonclient's RequestRouter

type SDKStructuredError added in v0.6.0

type SDKStructuredError struct {
	Error       string    `json:"error"`
	ID          uuid.UUID `json:"id"`
	SecondaryID uuid.UUID `json:"secondary_id"`
	Identical   bool      `json:"identical"`
}

SDKStructuredError is the standard structured error returned by our APIs for SDK clients to handle

func GetDetailedErrorInfo added in v0.6.4

func GetDetailedErrorInfo(err error) *SDKStructuredError

GetDetailedErrorInfo returns detailed information about the error if available and nil otherwise

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL