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 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 IClient interface {
Do(*http.Request) (*http.Response, error)
}
http.Client
supports it out of box.
Decorator is like a middleware:
type DecoratorFunc func(IClient) IClient
Kapusta provides some helpful decorators for you:
HeadersDecorator(values map[string]string)
Adds headers to requestsHeaderDecorator(name, value string)
Like headers, but add only one header.RecoverDecorator()
Converts all panics into errorsBaseURLDecorator(baseURL string)
Replaces scheme and host to baseURL value.
client := http.DefaultClient
decoratedClient := kapusta.Decorate(
client,
decorator.HeaderDecorator("X-Auth", "123"),
decorator.RecoverDecorator(), // better to place it last to recover panics from decorators too
)
There are two ways of creating new decorators.
You can create some new struct:
struct AwesomeStuffClient {
client kapusta.Client
}
func(c *AwesomeStuffClient) Do(r *http.Request) (*http.Response, error) {
// some stuff before call
res, err := c.client.Do(r)
// some stuff after call
return res, err
}
func AwesomeStuffDecorator(c kapusta.IClient) kapusta.IClient {
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.IClient) kapusta.IClient {
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
})
}
Sometimes it`s required to pass some params in decorator, for details see Headers decorator.