allow overriding the Logger used by Proxy

This commit is contained in:
Harrison Healey 2019-04-22 19:49:45 -04:00 committed by Will Norris
parent e1558d5626
commit d4246a08fd
2 changed files with 73 additions and 6 deletions

View file

@ -61,6 +61,9 @@ type Proxy struct {
// absolute.
DefaultBaseURL *url.URL
// The Logger used by the image proxy
Logger *log.Logger
// SignatureKey is the HMAC key used to verify signed requests.
SignatureKey []byte
@ -105,7 +108,7 @@ func NewProxy(transport http.RoundTripper, cache Cache) *Proxy {
CachingClient: client,
log: func(format string, v ...interface{}) {
if proxy.Verbose {
log.Printf(format, v...)
proxy.logf(format, v...)
}
},
},
@ -141,13 +144,13 @@ func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
req, err := NewRequest(r, p.DefaultBaseURL)
if err != nil {
msg := fmt.Sprintf("invalid request URL: %v", err)
log.Print(msg)
p.log(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
if err := p.allowed(req); err != nil {
log.Printf("%s: %v", err, req)
p.logf("%s: %v", err, req)
http.Error(w, msgNotAllowed, http.StatusForbidden)
return
}
@ -166,7 +169,7 @@ func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
if err != nil {
msg := fmt.Sprintf("error fetching remote image: %v", err)
log.Print(msg)
p.log(msg)
http.Error(w, msg, http.StatusInternalServerError)
return
}
@ -175,7 +178,7 @@ func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
cached := resp.Header.Get(httpcache.XFromCache)
if p.Verbose {
log.Printf("request: %+v (served from cache: %t)", *actualReq, cached == "1")
p.logf("request: %+v (served from cache: %t)", *actualReq, cached == "1")
}
copyHeader(w.Header(), resp.Header, "Cache-Control", "Last-Modified", "Expires", "Etag", "Link")
@ -193,7 +196,7 @@ func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
contentType = peekContentType(b)
}
if resp.ContentLength != 0 && !contentTypeMatches(p.ContentTypes, contentType) {
log.Printf("content-type not allowed: %q", contentType)
p.logf("content-type not allowed: %q", contentType)
http.Error(w, msgNotAllowed, http.StatusForbidden)
return
}
@ -368,6 +371,22 @@ func should304(req *http.Request, resp *http.Response) bool {
return false
}
func (p *Proxy) log(v ...interface{}) {
if p.Logger != nil {
p.Logger.Print(v...)
} else {
log.Print(v...)
}
}
func (p *Proxy) logf(format string, v ...interface{}) {
if p.Logger != nil {
p.Logger.Printf(format, v...)
} else {
log.Printf(format, v...)
}
}
// TransformingTransport is an implementation of http.RoundTripper that
// optionally transforms images using the options specified in the request URL
// fragment.