rest

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2024 License: Apache-2.0 Imports: 13 Imported by: 25

Documentation

Overview

Package rest provides an extended rest.Client with optional behaviours like rate limiting, request/response logging, etc.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Is4xxError added in v0.5.0

func Is4xxError(resp *http.Response) bool

func Is5xxError added in v0.5.0

func Is5xxError(resp *http.Response) bool

func IsSuccess added in v0.5.0

func IsSuccess(resp *http.Response) bool

func RetryIfNotSuccess

func RetryIfNotSuccess(resp *http.Response) bool

RetryIfNotSuccess is a basic retry function which will retry on any non 2xx status code.

func RetryIfTooManyRequests added in v0.7.0

func RetryIfTooManyRequests(resp *http.Response) bool

RetryIfTooManyRequests return true for responses with status code Too Many Requests (429).

func RetryOnFailureExcept404 added in v0.7.0

func RetryOnFailureExcept404(resp *http.Response) bool

RetryOnFailureExcept404 returns true for all failed responses except those with status not found.

func ReusableReader

func ReusableReader(r io.ReadCloser) (io.ReadCloser, error)

Types

type Client

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

Client represents a general HTTP client

func NewClient

func NewClient(baseURL *url.URL, httpClient *http.Client, opts ...Option) *Client

NewClient creates a new instance of the Client with specified options.

func (*Client) BaseURL added in v0.2.0

func (c *Client) BaseURL() *url.URL

BaseURL returns the base url configured for this client

func (*Client) DELETE

func (c *Client) DELETE(ctx context.Context, endpoint string, options RequestOptions) (*http.Response, error)

DELETE sends a DELETE request to the specified endpoint. If you wish to receive logs from this method supply a logger inside the context using logr.NewContext.

func (*Client) Do added in v0.5.0

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do executes the given request and returns a raw *http.Response

func (*Client) GET

func (c *Client) GET(ctx context.Context, endpoint string, options RequestOptions) (*http.Response, error)

GET sends a GET request to the specified endpoint. If you wish to receive logs from this method supply a logger inside the context using logr.NewContext.

func (*Client) PATCH added in v0.6.0

func (c *Client) PATCH(ctx context.Context, endpoint string, body io.Reader, options RequestOptions) (*http.Response, error)

PATCH sends a PATCH request to the specified endpoint with the given body. If you wish to receive logs from this method supply a logger inside the context using logr.NewContext.

func (*Client) POST

func (c *Client) POST(ctx context.Context, endpoint string, body io.Reader, options RequestOptions) (*http.Response, error)

POST sends a POST request to the specified endpoint with the given body. If you wish to receive logs from this method supply a logger inside the context using logr.NewContext.

func (*Client) PUT

func (c *Client) PUT(ctx context.Context, endpoint string, body io.Reader, options RequestOptions) (*http.Response, error)

PUT sends a PUT request to the specified endpoint with the given body. If you wish to receive logs from this method supply a logger inside the context using logr.NewContext.

func (*Client) SetHeader

func (c *Client) SetHeader(key, value string)

SetHeader sets a custom header for the HTTP client.

type Clock

type Clock interface {
	Now() time.Time
	After(d time.Duration) <-chan time.Time
}

type ConcurrentRequestLimiter

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

ConcurrentRequestLimiter represents a component for limiting concurrent requests.

func NewConcurrentRequestLimiter

func NewConcurrentRequestLimiter(maxConcurrent int) *ConcurrentRequestLimiter

NewConcurrentRequestLimiter creates a new instance of ConcurrentRequestLimiter with the specified limit to apply.

func (*ConcurrentRequestLimiter) Acquire

func (c *ConcurrentRequestLimiter) Acquire()

Acquire acquires a slot from the concurrent request limiter to check for maximum concurrent requests.

func (*ConcurrentRequestLimiter) Release

func (c *ConcurrentRequestLimiter) Release()

Release releases a slot from the concurrent request limiter to allow subsequent requests to proceed.

type HTTPListener

type HTTPListener struct {
	Callback func(response RequestResponse)
}

HTTPListener is a struct that can be used to listen for HTTP requests and responses and invoke a user-defined callback function.

type Option

type Option func(*Client)

Option represents a functional Option for the Client.

func WithConcurrentRequestLimit

func WithConcurrentRequestLimit(maxConcurrent int) Option

WithConcurrentRequestLimit sets the maximum number of concurrent requests allowed.

func WithHTTPListener

func WithHTTPListener(listener *HTTPListener) Option

WithHTTPListener sets the HTTPListener for the Client.

func WithRateLimiter

func WithRateLimiter() Option

WithRateLimiter activates a RateLimiter for the Client. The RateLimiter will block subsequent Client calls after a 429 status code is received until the mandated reset time is reached. If the server should not reply with an X-RateLimit-Reset header, a default delay is enforced. Note that a Client with RateLimiter will not automatically retry an API call after a limit was hit, but return the Too Many Requests 429 Response to you. If the Client should retry on errors, configure RetryOptions as well.

func WithRetryOptions added in v0.7.0

func WithRetryOptions(opts *RetryOptions) Option

WithRetryOptions sets the RetryOptions for the Client.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the request timeout for the Client.

type RateLimiter

type RateLimiter struct {
	Lock  sync.RWMutex
	Clock Clock
	// contains filtered or unexported fields
}

func NewRateLimiter

func NewRateLimiter() *RateLimiter

func (*RateLimiter) Update

func (rl *RateLimiter) Update(ctx context.Context, status int, headers http.Header)

func (*RateLimiter) Wait

func (rl *RateLimiter) Wait(ctx context.Context)

Wait blocks in case a hard API limit was reached, or the request/second limit was exceeded. In case of a hard limit, the method will block until after its reset time is reached. In case of the soft request/second limit it will block until requests are available again. See rate.Limiter for details on how soft-limits works.

type RequestInfo

type RequestInfo struct {
	Method string `json:"method"` // The HTTP method of the request.
	URL    string `json:"url"`    // The full URL of the request
}

RequestInfo holds information about the original request that led to this response

type RequestOptions

type RequestOptions struct {
	// QueryParams are HTTP query parameters that shall be appended
	// to the endpoint url
	QueryParams url.Values

	// ContentType is the "Content-Type" HTTP header that shall be used
	// during a request. A "Content-Type" header configured for the client
	// will be overwritten for the particular request
	ContentType string

	// CustomShouldRetryFunc optionally overrides the ShouldRetryFunc of
	// the RetryOptions specified for the client.
	CustomShouldRetryFunc RetryFunc
}

RequestOptions are additional options that should be applied to a request

type RequestResponse

type RequestResponse struct {
	ID        string         // ID to identify and correlate requests to responses
	Timestamp time.Time      // Timestamp of the recorded request/response
	Request   *http.Request  // HTTP request
	Response  *http.Response // HTTP response
	Error     error          // Error, if any, during request/response
}

RequestResponse represents a recorded HTTP request and response.

func (*RequestResponse) IsRequest

func (r *RequestResponse) IsRequest() (*http.Request, bool)

IsRequest checks if the RequestResponse value represents an HTTP request.

It returns a pointer to an http.Request and true if the RequestResponse contains a request. If the RequestResponse does not contain a request, it returns nil and false.

func (*RequestResponse) IsResponse

func (r *RequestResponse) IsResponse() (*http.Response, bool)

IsResponse checks if the RequestResponse value represents an HTTP response.

It returns a pointer to an http.Response and true if the RequestResponse contains a response. If the RequestResponse does not contain a response, it returns nil and false.

type RetryFunc added in v0.7.0

type RetryFunc func(resp *http.Response) bool

type RetryOptions added in v0.7.0

type RetryOptions struct {
	DelayAfterRetry time.Duration
	MaxRetries      int
	ShouldRetryFunc RetryFunc
}

RetryOptions represents a component for retrying failed HTTP requests.

Jump to

Keyboard shortcuts

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