0
Fork 0
mirror of https://github.com/willnorris/imageproxy.git synced 2024-12-30 22:34:18 -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 { if err := p.Director(outreq); err != nil {
p.logf("http: proxy error: %v", err) p.writeError(rw, err)
rw.WriteHeader(http.StatusBadGateway)
return return
} }
@ -182,8 +181,7 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
res, err := transport.RoundTrip(outreq) res, err := transport.RoundTrip(outreq)
if err != nil { if err != nil {
p.logf("http: proxy error: %v", err) p.writeError(rw, err)
rw.WriteHeader(http.StatusBadGateway)
return return
} }
@ -203,8 +201,7 @@ func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if p.ModifyResponse != nil { if p.ModifyResponse != nil {
if err := p.ModifyResponse(res); err != nil { if err := p.ModifyResponse(res); err != nil {
p.logf("http: proxy error: %v", err) p.writeError(rw, err)
rw.WriteHeader(http.StatusBadGateway)
return 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) { func (p *ReverseProxy) copyResponse(dst io.Writer, src io.Reader) {
if p.FlushInterval != 0 { if p.FlushInterval != 0 {
if wf, ok := dst.(writeFlusher); ok { if wf, ok := dst.(writeFlusher); ok {