util

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2025 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRequestFailed     = errors.New("request failed")
	ErrResponseParsing   = errors.New("response parsing failed")
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
	ErrTimeout           = errors.New("request timeout")
)

Functions

This section is empty.

Types

type HTTPClient

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

func NewHTTPClient

func NewHTTPClient(config HTTPClientConfig) *HTTPClient

NewHTTPClient creates a new instance of HTTPClient with the provided configuration. It sets default values for MaxRequestTimeout, RequestsPerSecond, MaxRetries, and RetryWaitTime if they are not provided in the config. It also initializes base headers if provided.

Parameters:

  • config: HTTPClientConfig containing configuration options for the HTTP client.

Returns:

  • *HTTPClient: A pointer to the newly created HTTPClient instance.

func (*HTTPClient) DoJSON

func (c *HTTPClient) DoJSON(ctx context.Context, method, url string, reqBody interface{}, respBody interface{}, headers map[string]string) error

DoJSON sends an HTTP request with a JSON body and decodes the JSON response.

Parameters:

  • ctx: The context for the request.
  • method: The HTTP method (e.g., "GET", "POST").
  • url: The URL to send the request to.
  • reqBody: The request body to be marshaled to JSON. Can be nil.
  • respBody: The response body to be unmarshaled from JSON. Can be nil.
  • headers: Additional headers to include in the request. Can be nil.

Returns:

  • error: An error if the request fails or the response cannot be parsed.

func (*HTTPClient) DoMultipartForm added in v1.1.0

func (c *HTTPClient) DoMultipartForm(ctx context.Context, method, url string, form map[string]interface{}, respBody interface{}) error

DoMultipartForm performs an HTTP request with multipart form data. It handles file uploads and form fields, applying rate limiting and retries.

Parameters:

  • ctx: Context for request cancellation and timeouts
  • method: HTTP method to use (e.g., "POST", "PUT")
  • url: Target URL for the request
  • form: Map containing form fields and file data. Special keys:
  • "file": Must be an io.Reader containing file data
  • "filename": String specifying the name for the uploaded file
  • respBody: Pointer to struct where JSON response will be unmarshaled (can be nil)

Returns:

  • error: nil if successful, otherwise:
  • ErrRateLimitExceeded if rate limit is hit
  • ErrRequestFailed for HTTP status >= 400
  • ErrResponseParsing for JSON unmarshaling errors
  • Other errors for form creation/writing failures

func (*HTTPClient) DoRequest

func (c *HTTPClient) DoRequest(ctx context.Context, method, url string, body []byte, headers map[string]string) ([]byte, error)

DoRequest sends an HTTP request with the specified method, URL, body, and headers, and returns the response body or an error if the request fails.

Parameters:

  • ctx: The context to control the request lifetime.
  • method: The HTTP method to use (e.g., "GET", "POST").
  • url: The URL to send the request to.
  • body: The request body as a byte slice.
  • headers: A map of additional headers to include in the request.

Returns:

  • A byte slice containing the response body.
  • An error if the request fails or the response status code is 400 or higher.

The function respects rate limiting and retries the request if necessary. It also sets base headers defined in the HTTPClient and additional headers provided in the headers parameter.

func (*HTTPClient) GetBaseHeaders

func (c *HTTPClient) GetBaseHeaders() map[string]string

GetBaseHeaders returns a copy of the base headers of the HTTP client. It acquires a read lock to ensure thread-safe access to the baseHeaders map.

func (*HTTPClient) GetClient

func (h *HTTPClient) GetClient() *fasthttp.Client

GetClient returns the underlying fasthttp.Client instance used by the HTTPClient. This allows for direct manipulation or configuration of the client if needed.

func (*HTTPClient) SetBaseHeaders

func (c *HTTPClient) SetBaseHeaders(headers map[string]string)

SetBaseHeaders sets the base headers for the HTTP client. It takes a map of headers as input and updates the client's base headers with the provided key-value pairs. The method is thread-safe as it locks the mutex before updating the headers and unlocks it after the update.

Parameters:

  • headers: A map[string]string containing the headers to be set.

Example:

headers := map[string]string{
    "Content-Type": "application/json",
    "Authorization": "Bearer token",
}
client.SetBaseHeaders(headers)

type HTTPClientConfig

type HTTPClientConfig struct {
	MaxRequestTimeout time.Duration
	RequestsPerSecond int
	MaxRetries        int
	RetryWaitTime     time.Duration
	BaseHeaders       map[string]string
}

type RateLimiter

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

func NewRateLimiter

func NewRateLimiter(requestsPerSecond int) *RateLimiter

NewRateLimiter creates a new RateLimiter that allows a specified number of requests per second. It initializes a ticker that ticks at intervals based on the requestsPerSecond parameter, and a buffered channel to hold the tokens.

Parameters:

  • requestsPerSecond: The number of requests allowed per second.

Returns:

  • *RateLimiter: A pointer to the newly created RateLimiter instance.

func (*RateLimiter) Wait

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

Wait blocks until a token is available or the context is done. It returns nil if a token is acquired, or an error if the context is done.

Parameters:

ctx - The context to use for cancellation.

Returns:

error - nil if a token is acquired, or the context's error if it is done.

type RetryConfig

type RetryConfig struct {
	MaxRetries    int
	RetryWaitTime time.Duration
}

Jump to

Keyboard shortcuts

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