zhttpclient

package
v0.18.3 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

zhttpclient Package

Overview

The zhttpclient package serves as an abstraction layer for http requests within Golang applications. Using Resty as a foundation, it provides convenient abstractions and backoff functions for common http requests.

Table of Contents

  1. Features
  2. Installation
  3. Usage

Features

  • Convenience Methods: Convenient methods for http operations.
  • Retry Mechanism: Automatic retries depending on configurable conditions.
  • Mocks: Provides mock implementations for the ZHTTPClient and ZRequest interface.

Installation

go get github.com/zondax/golem/pkg/zhttpclient

Usage

Here's a quick example demonstrating how to use it.

import (
    "github.com/zondax/golem/pkg/zhttpclient"
)

func main() {
    config := &zhttpclient.Config{
        Timeout: ..,
        TLSConfig: ...,
        BaseClient: ..., // a pre-configured http.Client
    }

    client, err := zhttpclient.New(config)
    if err != nil {
        panic(err)
    }


    // all requests with this client will use it
    retry := &RetryPolicy{
        MaxAttempts: ..., // max number of retries
        WaitBeforeRetry: ..., // the minimum default wait before retry
        MaxWaitBeforeRetry: ..., // the maximum cap for the wait before retry
    }

    // The default backoff policy is Exponential Jitter provided by resty

    retry.SetLinearBackoff(duration)
    // or
    retry.SetExponentialBackoff(duration)

    // top-level retry policy
    client.SetRetryPolicy(retry)

    req := client.NewRequest().SetURL(srv.URL).SetHeaders(headers)

    // GET
    resp,err := req.SetQueryParams(getParams).
    		SetRetryPolicy(&zhttpclient.RetryPolicy{}). // override client retry policy
      	Get(ctx)

    // POST
    resp,err := req.SetBody(body).Post(ctx)
    fmt.Println(resp.Code,string(resp.Body))

    // AUTO-decode response
    resp,err := req.SetBody(body).SetResponse(&MyRespStruct{}).SetError(&MyErrStruct{}).Post(ctx)
    if resp.Response != nil{
    	parsedResp := resp.Response.(*MyRespStruct)
    }
    if resp.Error != nil{
    	parsedErr := resp.Error.(*MyErrStruct)
    }

    // Do raw request
    req, _ := http.NewRequest(method, URL, body)
    resp,err := client.Do(ctx,req)
    fmt.Println(string(resp.Body))

}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BackoffFn

type BackoffFn func(attempt uint, r *http.Response, lastErr error) time.Duration

BackoffFn is a function that returns a backoff duration.

type Config

type Config struct {
	Timeout    time.Duration
	TLSConfig  *tls.Config
	BaseClient *http.Client
}

type MockZHTTPClient

type MockZHTTPClient struct {
	mock.Mock
}

MockZHTTPClient is an autogenerated mock type for the ZHTTPClient type

func NewMockZHTTPClient

func NewMockZHTTPClient(t mockConstructorTestingTNewMockZHTTPClient) *MockZHTTPClient

NewMockZHTTPClient creates a new instance of MockZHTTPClient. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.

func (*MockZHTTPClient) Do

func (_m *MockZHTTPClient) Do(ctx context.Context, req *http.Request) (*Response, error)

Do provides a mock function with given fields: ctx, req

func (*MockZHTTPClient) NewRequest

func (_m *MockZHTTPClient) NewRequest() ZRequest

NewRequest provides a mock function with given fields:

func (*MockZHTTPClient) SetRetryPolicy

func (_m *MockZHTTPClient) SetRetryPolicy(retryPolicy *RetryPolicy) ZHTTPClient

SetRetryPolicy provides a mock function with given fields: retryPolicy

type MockZRequest

type MockZRequest struct {
	mock.Mock
}

MockZRequest is an autogenerated mock type for the ZRequest type

func NewMockZRequest

func NewMockZRequest(t mockConstructorTestingTNewMockZRequest) *MockZRequest

NewMockZRequest creates a new instance of MockZRequest. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.

func (*MockZRequest) Get

func (_m *MockZRequest) Get(ctx context.Context) (*Response, error)

Get provides a mock function with given fields: ctx

func (*MockZRequest) Post

func (_m *MockZRequest) Post(ctx context.Context) (*Response, error)

Post provides a mock function with given fields: ctx

func (*MockZRequest) SetBody

func (_m *MockZRequest) SetBody(body io.Reader) ZRequest

SetBody provides a mock function with given fields: body

func (*MockZRequest) SetError

func (_m *MockZRequest) SetError(err interface{}) ZRequest

SetError provides a mock function with given fields: err

func (*MockZRequest) SetHeaders

func (_m *MockZRequest) SetHeaders(headers map[string]string) ZRequest

SetHeaders provides a mock function with given fields: headers

func (*MockZRequest) SetQueryParams

func (_m *MockZRequest) SetQueryParams(params url.Values) ZRequest

SetQueryParams provides a mock function with given fields: params

func (*MockZRequest) SetResult

func (_m *MockZRequest) SetResult(result interface{}) ZRequest

SetResult provides a mock function with given fields: result

func (*MockZRequest) SetRetryPolicy

func (_m *MockZRequest) SetRetryPolicy(retryPolicy *RetryPolicy) ZRequest

SetRetryPolicy provides a mock function with given fields: retryPolicy

func (*MockZRequest) SetURL

func (_m *MockZRequest) SetURL(_a0 string) ZRequest

SetURL provides a mock function with given fields: _a0

type Response

type Response struct {
	Code   int
	Result interface{}
	Error  interface{}
	Body   []byte
}

func (*Response) IsError added in v0.17.5

func (r *Response) IsError() bool

IsError returns true if the statusCode is >= 400

type RetryPolicy

type RetryPolicy struct {
	// MaxAttempts is the maximum number of retries
	MaxAttempts int
	// WaitBeforeRetry is the minimum default wait before retry
	WaitBeforeRetry time.Duration
	// MaxWaitBeforeRetry is the maximum cap for the wait before retry
	MaxWaitBeforeRetry time.Duration
	// contains filtered or unexported fields
}

func (*RetryPolicy) SetBackoff

func (r *RetryPolicy) SetBackoff(fn BackoffFn)

SetBackoff sets a custom backoff function to be used to calculate the sleep duration between retries.

func (*RetryPolicy) SetExponentialBackoff

func (r *RetryPolicy) SetExponentialBackoff(duration time.Duration)

SetExponentialBackoff sets an exponential base 2 delay ( duration * 2 ^ attempt ) for each attempt.

func (*RetryPolicy) SetLinearBackoff

func (r *RetryPolicy) SetLinearBackoff(duration time.Duration)

SetLinearBackoff sets a constant sleep duration between retries.

func (*RetryPolicy) WithCodes

func (r *RetryPolicy) WithCodes(codes ...int) *RetryPolicy

WithCodes specifies the response status codes which trigger a retry.

type ZHTTPClient

type ZHTTPClient interface {
	SetRetryPolicy(retryPolicy *RetryPolicy) ZHTTPClient
	NewRequest() ZRequest
	Do(ctx context.Context, req *http.Request) (*Response, error)
}

func New

func New(config Config) ZHTTPClient

type ZRequest

type ZRequest interface {
	SetURL(url string) ZRequest
	SetHeaders(headers map[string]string) ZRequest
	SetBody(body io.Reader) ZRequest
	SetQueryParams(params url.Values) ZRequest
	SetRetryPolicy(retryPolicy *RetryPolicy) ZRequest
	SetResult(result interface{}) ZRequest
	SetError(err interface{}) ZRequest
	Post(ctx context.Context) (*Response, error)
	Get(ctx context.Context) (*Response, error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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