Jonas
Jonas

Reputation: 5149

How to add default header fields from http.Client

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?

Upvotes: 11

Views: 10792

Answers (1)

leaf bebop
leaf bebop

Reputation: 8222

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

Upvotes: 26

Related Questions