From 9aeb23bc03d050772a207fdd66c65c7d6e9e5778 Mon Sep 17 00:00:00 2001 From: Peter Fern Date: Mon, 5 Jan 2015 20:36:17 +1100 Subject: [PATCH] Preserve HTTP headers on redirect This ensures things like our custom UserAgent get preserved if the server does a redirect (my mirror enforces SSL, for example). See golang/go#4800 Code cribbed from gyuho/gon --- gomusicbrainz.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/gomusicbrainz.go b/gomusicbrainz.go index 6b212c8..213efd2 100644 --- a/gomusicbrainz.go +++ b/gomusicbrainz.go @@ -74,6 +74,7 @@ package gomusicbrainz import ( "encoding/xml" "errors" + "fmt" "log" "net/http" "net/url" @@ -111,6 +112,25 @@ func (c *WS2Client) getReqeust(data interface{}, params url.Values, endpoint str client := &http.Client{} + defaultRedirectLimit := 30 + + // Preserve headers on redirect + // See: https://github.com/golang/go/issues/4800 + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) > defaultRedirectLimit { + return fmt.Errorf("%d consecutive requests(redirects)", len(via)) + } + if len(via) == 0 { + // No redirects + return nil + } + // mutate the subsequent redirect requests with the first Header + for key, val := range via[0].Header { + req.Header[key] = val + } + return nil + } + reqUrl := *c.WS2RootURL reqUrl.Path = path.Join(reqUrl.Path, endpoint) reqUrl.RawQuery = params.Encode()