swiftreq

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2023 License: MIT Imports: 14 Imported by: 0

README

SwiftReq

SwiftReq is a Golang library designed to simplify HTTP requests in your services. It offers a set of features to enhance your interaction with external services.

Features

  • Generics: Utilize generics for seamless HTTP response handling.
  • Retry: Enable automatic retries with options for exponential or linear jitter backoff.
  • Caching: Enable caching with set time to live.
  • Logging: Easily log all requests for better visibility.
  • Performance Monitor: Monitor and log responses exceeding defined thresholds.
  • Authentication: utomatically include access tokens and refresh them in the background.

Getting Started

Installation
go get -u github.com/liviudnicoara/swiftreq
Usage

Making simple requests


// GET request
posts, err := swiftreq.Get[[]Post](BASE_URL + "/posts").Do(context.Background())

// POST request
resp, err := swiftreq.Post[Post](BASE_URL+"/posts", post).Do(context.Background())

// PUT request
resp, err = swiftreq.Put[Post](BASE_URL+"/posts/1", post).Do(context.Background())

// DELETE request
resp, err = swiftreq.Delete[Post](BASE_URL + "/posts/1").Do(context.Background())
	

Making custom requests


post, err := swiftreq.Get[Post](BASE_URL + "/posts/1").
	WithQueryParameters(map[string]string{"page": "1"}).
	WithHeaders(map[string]string{"Content-Type": "application/json"}).
	Do(context.Background())

Setting retry


// Request with exponential backoff (default min wait is 500ms and max wait is 10s)
resp, err := swiftreq.Get[string]("http://localhost:3000/retry").
	WithRequestExecutor(swiftreq.Default().
		WithExponentialRetry(5)).
	Do(context.Background())

// Request with liniar backoff (default min wait is 500ms and max wait is 10s)
resp, err := swiftreq.Get[string]("http://localhost:3000/retry").
	WithRequestExecutor(swiftreq.Default().
		WithLinearRetry(5)).
	Do(context.Background())

Caching responses

swiftreq.Default(). 
	AddCaching(100 * time.Second) // Get requests will be cached in memory for 100 seconds

post, err := swiftreq.Get[Post](BASE_URL + "/posts/1").
	Do(context.Background())

Logging and performance monitor

swiftreq.Default(). 
	AddLogging(slog.Default()).                                // add logger
	AddPerformanceMonitor(10*time.Millisecond, slog.Default()) // add performance monitor

// Requests will be logged. 
// If response time is over 10 ms, a warning will be logged.
post, err := swiftreq.Get[Post](BASE_URL + "/posts/1").
	Do(context.Background())

Authentication


re := swiftreq.Default()
	.WithAuthorization("Token", func() (token string, lifeSpan time.Duration, err error) {
		// Provide the token retrieval.
		resp, err := swiftreq.Get[string]("http://localhost:3000/auth").
			WithRequestExecutor(swiftreq.NewRequestExecutor(*http.DefaultClient)).
			WithHeaders(map[string]string{"Credentials": "user:pass"}).
			Do(context.Background())

		return resp.Token resp.LifeSpan, resp.Error
	})


resp, err := swiftreq.Get[string]("http://localhost:3000/page").
	WithRequestExecutor(re).
	Do(context.Background())

License

This project is licensed under the MIT License - see the License file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDefault

func SetDefault(re *RequestExecutor)

SetDefault makes re the default RequestExecutor.

Types

type Error

type Error struct {
	Message    string
	Cause      error
	StatusCode int
}

Error represents an error that may occur during an HTTP request.

func (*Error) Error

func (e *Error) Error() string

Error returns a formatted error message including the original cause and status code.

type Request

type Request[T any] struct {
	// contains filtered or unexported fields
}

Request represents an HTTP request with fluent methods for customization.

func Delete

func Delete[T any](url string) *Request[T]

Delete creates a new HTTP DELETE request.

func Get

func Get[T any](url string) *Request[T]

Get creates a new HTTP GET request.

func Post

func Post[T any](url string, payload interface{}) *Request[T]

Post creates a new HTTP POST request with the specified payload.

func Put

func Put[T any](url string, payload interface{}) *Request[T]

Put creates a new HTTP PUT request with the specified payload.

func (*Request[T]) Do

func (r *Request[T]) Do(ctx context.Context) (*T, error)

Do executes the HTTP request and returns the response.

func (*Request[T]) WithHeaders

func (r *Request[T]) WithHeaders(headers map[string]string) *Request[T]

WithHeaders sets the headers for the request.

func (*Request[T]) WithMethod

func (r *Request[T]) WithMethod(httpMethod string) *Request[T]

WithMethod sets the HTTP method for the request.

func (*Request[T]) WithPayload

func (r *Request[T]) WithPayload(payload interface{}) *Request[T]

WithPayload sets the payload for the request.

func (*Request[T]) WithQueryParameters

func (r *Request[T]) WithQueryParameters(params map[string]string) *Request[T]

WithQueryParameters sets the query parameters for the request.

func (*Request[T]) WithRequestExecutor

func (r *Request[T]) WithRequestExecutor(re *RequestExecutor) *Request[T]

WithRequestExecutor sets the RequestExecutor for the request.

func (*Request[T]) WithURL

func (r *Request[T]) WithURL(url string) *Request[T]

WithURL sets the URL for the request.

type RequestExecutor

type RequestExecutor struct {
	MinWaitRetry time.Duration
	MaxWaitRetry time.Duration

	Logger *slog.Logger
	// contains filtered or unexported fields
}

RequestExecutor is a struct representing an HTTP client with middleware support.

func Default

func Default() *RequestExecutor

Default returns the default RequestExecutor.

func NewRequestExecutor

func NewRequestExecutor(client http.Client) *RequestExecutor

NewRequestExecutor creates a new RequestExecutor with the provided http.Client.

func (*RequestExecutor) AddCaching

func (re *RequestExecutor) AddCaching(ttl time.Duration) *RequestExecutor

AddCaching adds caching middleware to the RequestExecutor with the specified TTL.

func (*RequestExecutor) AddLogging

func (re *RequestExecutor) AddLogging(logger *slog.Logger) *RequestExecutor

AddLogging adds logging middleware to the RequestExecutor.

func (*RequestExecutor) AddPerformanceMonitor

func (re *RequestExecutor) AddPerformanceMonitor(threshold time.Duration, logger *slog.Logger) *RequestExecutor

AddPerformanceMonitor adds performance monitoring middleware to the RequestExecutor.

func (*RequestExecutor) WithAuthorization

func (re *RequestExecutor) WithAuthorization(schema string, authorize middlewares.AuthorizeFunc) *RequestExecutor

WithAuthorization adds authorization middleware to the RequestExecutor with the specified schema and authorization function.

func (*RequestExecutor) WithExponentialRetry

func (re *RequestExecutor) WithExponentialRetry(retry int) *RequestExecutor

WithExponentialRetry adds exponential retry middleware to the RequestExecutor with the specified retry count.

func (*RequestExecutor) WithLinearRetry added in v1.0.1

func (re *RequestExecutor) WithLinearRetry(retry int) *RequestExecutor

WithLinearRetry adds linear retry middleware to the RequestExecutor with the specified retry count.

func (*RequestExecutor) WithMiddleware

func (re *RequestExecutor) WithMiddleware(handler middlewares.Middleware) *RequestExecutor

WithMiddleware adds a single middleware to the RequestExecutor.

func (*RequestExecutor) WithMiddlewares

func (re *RequestExecutor) WithMiddlewares(handlers ...middlewares.Middleware) *RequestExecutor

WithMiddlewares adds multiple middlewares to the RequestExecutor.

func (*RequestExecutor) WithTimeout

func (re *RequestExecutor) WithTimeout(timeout time.Duration) *RequestExecutor

WithTimeout sets the timeout for the RequestExecutor.

type Response

type Response struct {
	Data       interface{}
	Success    bool
	Error      error
	StatusCode int
}

Response represents the result of an HTTP request.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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