interceptor

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2024 License: MIT Imports: 5 Imported by: 0

README

interceptor

Simple HTTP request interceptor

The concept
  • define the interceptor to use for every outgoing request
  • create a request
  • provide an HTTP client
  • send the request with interceptor
Examples
  • retry while destination service is unavailable
interceptor.New(
    interceptor.Retry(serviceConfig.Client.MaxRetries),
    interceptor.WithInterval(time.Duration(serviceConfig.Client.RetryInterval)),
    interceptor.WhileFails(func(r *http.Response) error {
        if r.StatusCode == 503 {
            return errors.ServiceUnavailable("service is unavailable")
        }

        return nil
    }),
).Then(http.DefaultClient).Do(req)
  • throttle
var (
    ticker = time.NewTicker(duration)
    icp = interceptor.New(interceptor.Throttle(ticker.C)).Then(http.DefaultClient)
)

icp.Do(req)
icp.Do(req)
. . .
icp.Do(req)

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Doer

type Doer interface {
	Do(req *http.Request) (*http.Response, error)
}

type DoerFunc

type DoerFunc func(req *http.Request) (*http.Response, error)

func (DoerFunc) Do

func (fn DoerFunc) Do(req *http.Request) (*http.Response, error)

type Interceptor

type Interceptor func(next Doer) Doer

func Log

func Log(
	debugfFunc, errorfFunc func(string, ...interface{}),
) Interceptor

func New

func New(interceptors ...Interceptor) Interceptor

func Retry

func Retry(tries int) Interceptor

Retry request interceptor, call `Retry(0)` means make a single call with no retry.

func Throttle added in v0.0.2

func Throttle(tick <-chan time.Time) Interceptor

Throttle provides an interceptor that delays client request waiting for a value from an input channel. Use `time.NewTicker(duration).C` or `time.Tick(duration)` as an input parameter.

Example:

var (
	ticker = time.NewTicker(duration)
	icp = interceptor.New(interceptor.Throttle(ticker.C)).Then(http.DefaultClient)
)

icp.Do(req)
icp.Do(req)
. . .
icp.Do(req)

func UntilStatusCodeIs

func UntilStatusCodeIs(status int) Interceptor

UntilStatusCodeIs returns an error until specified response status code is received.

func WhileFails

func WhileFails(checkFunc func(*http.Response) error) Interceptor

WhileFails is one of the configurable parts of retry strategy. Specify the function to check the response and return descriptive error message if needed.

func WithInterval

func WithInterval(duration time.Duration) Interceptor

func (Interceptor) Then

func (icp Interceptor) Then(doer Doer) Doer

func (Interceptor) Use

func (icp Interceptor) Use(interceptors ...Interceptor) Interceptor

Jump to

Keyboard shortcuts

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