Skip to content

proposal: net/http: set default headers in http.Client #64309

Open
@hebelsan

Description

@hebelsan

In my application I use a struct with an http.client
At all points where a request is made with this client, I would like to set my own custom user agent.
But here is the problem, I don't see a nice way to set this user agent as default in my http.client.

My first idea is to manipulate the transport and the associated http.RoundTripper:

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)
}

However, The documentation for http.RoundTripper says: "RoundTrip should not modify the request, except for consuming and closing the Request's Body."

Alternatively, I can only see the possibility of manually setting the header in each request object created, but this can easily be forgotten and thus lead to inconsistencies.

It would be cool if you could specify default headers when creating the http.client, which would then be set automatically for each request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions