From 3444fd9cb479db44758600de90f0f60dd1e6970e Mon Sep 17 00:00:00 2001 From: Hugues Alary Date: Mon, 31 Jul 2017 18:28:48 -0700 Subject: [PATCH] allow custom User-Agent when fetching remote image Closes #83 --- cmd/imageproxy/main.go | 2 ++ imageproxy.go | 16 +++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cmd/imageproxy/main.go b/cmd/imageproxy/main.go index e9149f8..9c6d04c 100644 --- a/cmd/imageproxy/main.go +++ b/cmd/imageproxy/main.go @@ -53,6 +53,7 @@ var timeout = flag.Duration("timeout", 0, "time limit for requests served by thi var verbose = flag.Bool("verbose", false, "print verbose logging messages") var version = flag.Bool("version", false, "Deprecated: this flag does nothing") var contentTypes = flag.String("contentTypes", "image/*", "comma separated list of allowed content types") +var userAgent = flag.String("userAgent", "willnorris/imageproxy", "specify the user-agent used by imageproxy when fetching images from origin website") func init() { flag.Var(&cache, "cache", "location to cache images (see https://github.com/willnorris/imageproxy#cache)") @@ -98,6 +99,7 @@ func main() { p.Timeout = *timeout p.ScaleUp = *scaleUp p.Verbose = *verbose + p.UserAgent = *userAgent server := &http.Server{ Addr: *addr, diff --git a/imageproxy.go b/imageproxy.go index 4152a86..c6c7b15 100644 --- a/imageproxy.go +++ b/imageproxy.go @@ -76,6 +76,9 @@ type Proxy struct { // ContentTypes specifies a list of content types to allow. An empty // list means all content types are allowed. ContentTypes []string + + // The User-Agent used by imageproxy when requesting origin image + UserAgent string } // NewProxy constructs a new proxy. The provided http RoundTripper will be @@ -150,7 +153,11 @@ func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) { return } - resp, err := p.Client.Get(req.String()) + actualReq, _ := http.NewRequest("GET", req.String(), nil) + if p.UserAgent != "" { + actualReq.Header.Set("User-Agent", p.UserAgent) + } + resp, err := p.Client.Do(actualReq) if err != nil { msg := fmt.Sprintf("error fetching remote image: %v", err) log.Print(msg) @@ -345,9 +352,8 @@ func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, er return t.Transport.RoundTrip(req) } - u := *req.URL - u.Fragment = "" - resp, err := t.CachingClient.Get(u.String()) + req.URL.Fragment = "" + resp, err := t.CachingClient.Do(req) if err != nil { return nil, err } @@ -368,7 +374,7 @@ func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, er img, err := Transform(b, opt) if err != nil { - log.Printf("error transforming image %s: %v", u.String(), err) + log.Printf("error transforming image %s: %v", req.URL.String(), err) img = b }