Middleware can be created with the defining function:
func(request *http.Request, next func(request *http.Request) (*http.Response, error)) (*http.Response, error)
Example:
client := chttp.NewClient(nil)
client.With(func(request *http.Request, next func(request *http.Request) (*http.Response, error)) (*http.Response, error) {
// before action
response, err := next(request)
// before action
return response, err
})
Adds a custom headers based on the request.
Example:
client := chttp.NewClient(nil)
client.With(middleware.CustomHeaders(func(request *http.Request) map[string]string {
if request.Method == http.MethodPost {
return map[string]string{
"Accept": "*/*",
}
}
return nil
}))
NB! Don't use it in production!
Dumps requests and responses in the logs.
Example:
client := chttp.NewClient(nil)
client.With(middleware.Debug(true, nil))
Adds a static headers.
Example:
client := chttp.NewClient(nil)
client.With(middleware.Headers(map[string]string{
"Accept": "*/*",
}))
Adds a Content-Type
and Accept
headers with the application/json
value.
Example:
client := chttp.NewClient(nil)
client.With(middleware.JSON())
Adds an OpenTracing logs and headers to the request.
Source: https://github.com/spyzhov/chttp-middleware-opentracing
import (
// ...
middleware "github.com/spyzhov/chttp-middleware-opentracing"
)
client := chttp.NewClient(nil)
client.With(middleware.Opentracing())
Adds short logs on each request.
Example:
client := chttp.NewClient(nil)
client.With(middleware.Trace(nil))
-
Cache(interface{Get(string,interface{}), Set(string,interface{})}, GetKey func(*http.Request) string)
Client-wide caching layer.
If
GetKey
return a blank string, then do not cache. -
Retry(GetCount func(*http.Request) int, BeforeRetry func (*http.Request, int) string)
Automatically send a retry request in case of failure.
GetCount
- returns the max retry amount.BeforeRetry
- should be called before retry.TODO: think about a structure as argument
struct {GetCount func(*http.Request) int, BeforeRetry func (*http.Request, int) string}