Setting the HTTP User Agent in Go


Here’s the smallest amount of code I could come up with to set the user agent when making a HTTP request in Go:

type UserAgent string

func (u UserAgent) RoundTrip(r *http.Request) (*http.Response, error) {
    r.Header.Set("User-Agent", string(u))
    return http.DefaultTransport.RoundTrip(r)
}

http.DefaultClient.Transport = UserAgent("my-great-program")

Note that this isn’t really legal, since the RoundTripper is not supposed to modify the request.