I want http.Client
to add additional header for all requests.
type MyClient struct {
http.Client
}
func (c *MyClient) Do(req *http.Request) (*http.Response, error) {
req.Header.Add("User-Agent", "go")
return c.Client.Do(req)
}
func Do
never gets called if I call func PostForm
that is using Do
. If there is no way how to mimic OOP, how to do it least painfully?
Custom HTTP headers can be used to filter requests or specify a value for the Accept header.
An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.
http.Client
has a field Transport
which is of type RoundTripper
- an interface type.
It provides us the option to change request (and response, of course) between.
You can create a custom type that wraps another RoundTripper
and adds the header in the custom type's RoundTrip
:
type AddHeaderTransport struct{
T http.RoundTripper
}
func (adt *AddHeaderTransport) RoundTrip(req *http.Request) (*http.Response,error) {
req.Header.Add("User-Agent", "go")
return adt.T.RoundTrip(req)
}
Full code on playground: https://play.golang.org/p/FbkpFlyFCm_F
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With