roundtrip.go 813 B

12345678910111213141516171819202122232425262728293031
  1. package httputil
  2. import "net/http"
  3. type userAgentTransport struct {
  4. userAgent string
  5. base http.RoundTripper
  6. }
  7. // NewUserAgentTransport creates a RoundTripper that attaches the configured user agent.
  8. func NewUserAgentTransport(userAgent string, base http.RoundTripper) http.RoundTripper {
  9. return &userAgentTransport{
  10. userAgent: userAgent,
  11. base: base,
  12. }
  13. }
  14. func (t userAgentTransport) RoundTrip(r *http.Request) (*http.Response, error) {
  15. // The specification of http.RoundTripper says that it shouldn't mutate
  16. // the request so make a copy of req.Header since this is all that is
  17. // modified.
  18. r2 := new(http.Request)
  19. *r2 = *r
  20. r2.Header = make(http.Header)
  21. for k, s := range r.Header {
  22. r2.Header[k] = s
  23. }
  24. r2.Header.Set("User-Agent", t.userAgent)
  25. r = r2
  26. return t.base.RoundTrip(r)
  27. }