It`s middleware approach for using http.Client. You can wrap your client with different functionality:
- log every request
- append auth headers
- use http cache
- use etcd/consul for service discovery
- and whatever you want!
Just like a cabbage!
Internal http package doesn`t have any interface for http clients, so Kapusta provides very simple client interface:
type Client interface {
Do( *http.Request) (*http.Response, error)
}
http.Client
supports it out of box!
type MiddlewareFunc func(Client) Client
Kapusta provides some helpful middlewares for you:
HeadersMiddleware(values map[string]string)
Adds headers to requestsHeaderMiddleware(name, value string)
Like headers, but add only one header.RecoverMiddleware()
Converts all panics into errorsBaseURLMiddleware(baseURL string)
Replaces scheme and host to baseURL value.
decoratedClient := kapusta.Chain(
http.DefaultClient,
middleware.HeaderMiddleware("X-Auth", "123"),
middleware.RecoverMiddleware(), // better to place it last to recover panics from middlewares too
)
There are two ways of creating new middleware.
You can create some new struct:
struct AwesomeStuffClient {
client kapusta.Client
}
func(c *AwesomeStuffClient) Do(ctx context.Context, r *http.Request) (*http.Response, error) {
// some stuff before call
res, err := c.client.Do(ctx, r)
// some stuff after call
return res, err
}
func AwesomeStuffDecorator(c kapusta.Client) kapusta.Client {
return &AwesomeStuffClient{client: c}
}
Or you can create just a function with type:
type ClientFunc func(*http.Request) (*http.Response, error)
So the same example will be looks like:
func AwesomeStuffDecorator(c kapusta.Client) kapusta.Client {
return kapusta.ClientFunc(func(r *http.Request) (*http.Response, error) {
// some stuff before call
res, err := c.client.Do(r)
// some stuff after call
return res, err
})
}
Also kapusta provides mock package for testing purposes.
client := mock.NewClient() // implements kapusta.Client
client.
Get("/path").
WithBody(`{"foo": "bar"}`).
WillReturn(200, `{"bar": "foo"}`)
// now you can inject client to your code.