Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add default header fields from http.Client

Tags:

go

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?

like image 449
Jonas Avatar asked Aug 01 '18 08:08

Jonas


People also ask

Can HTTP headers be custom?

Custom HTTP headers can be used to filter requests or specify a value for the Accept header.

What is header in HttpClient?

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.


1 Answers

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

like image 81
leaf bebop Avatar answered Oct 17 '22 05:10

leaf bebop