0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-16 21:56:43 -05:00

reverseproxy: refactor error printing

allow errors to specify HTTP status code that should be returned.
This commit is contained in:
Will Norris 2017-06-17 08:49:21 -04:00
parent 457e1fbe35
commit 038e10f436

View file

@ -130,8 +130,7 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
if err := p.Director(outreq); err != nil {
p.logf("http: proxy error: %v", err)
rw.WriteHeader(http.StatusBadGateway)
p.writeError(rw, err)
return
}
@ -182,8 +181,7 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
res, err := transport.RoundTrip(outreq)
if err != nil {
p.logf("http: proxy error: %v", err)
rw.WriteHeader(http.StatusBadGateway)
p.writeError(rw, err)
return
}
@ -203,8 +201,7 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if p.ModifyResponse != nil {
if err := p.ModifyResponse(res); err != nil {
p.logf("http: proxy error: %v", err)
rw.WriteHeader(http.StatusBadGateway)
p.writeError(rw, err)
return
}
}
@ -247,6 +244,20 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
}
}
// writerError writes err to the http response.
func (p *ReverseProxy) writeError(w http.ResponseWriter, err error) {
type statusCoder interface {
StatusCode() int
}
p.logf("http: proxy error: %v", err)
code := http.StatusBadGateway
if err, ok := err.(statusCoder); ok {
code = err.StatusCode()
}
http.Error(w, err.Error(), code)
}
func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
if p.FlushInterval != 0 {
if wf, ok := dst.(writeFlusher); ok {