Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hebelsan opened this issue Nov 21, 2023 · 3 comments
Open

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

hebelsan opened this issue Nov 21, 2023 · 3 comments
Labels
Milestone

Comments

@hebelsan
Copy link

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.

@gopherbot gopherbot added this to the Proposal milestone Nov 21, 2023
@seankhliao seankhliao changed the title proposal: affected/package: net/http: http.client default headers proposal: net/http: set default headers in http.Client Nov 21, 2023
@seankhliao
Copy link
Member

see also #59266

@seankhliao
Copy link
Member

also #13837 which was folded into #23707

@Jorropo
Copy link
Member

Jorropo commented Nov 22, 2023

I agree with #59266 on this subject, I put that on the RoundTripper implementation. Because there is no equivalent http.Client interface.
I don't think there is more value doing that in the client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

4 participants