traefik/vendor/github.com/vulcand/oxy/utils/handler.go

63 lines
1.6 KiB
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
package utils
import (
2018-08-20 08:38:03 +00:00
"context"
2017-02-07 21:33:23 +00:00
"io"
"net"
"net/http"
2018-08-20 08:38:03 +00:00
log "github.com/sirupsen/logrus"
2017-02-07 21:33:23 +00:00
)
2018-08-20 08:38:03 +00:00
// StatusClientClosedRequest non-standard HTTP status code for client disconnection
const StatusClientClosedRequest = 499
// StatusClientClosedRequestText non-standard HTTP status for client disconnection
const StatusClientClosedRequestText = "Client Closed Request"
// ErrorHandler error handler
2017-02-07 21:33:23 +00:00
type ErrorHandler interface {
ServeHTTP(w http.ResponseWriter, req *http.Request, err error)
}
2018-08-20 08:38:03 +00:00
// DefaultHandler default error handler
2017-02-07 21:33:23 +00:00
var DefaultHandler ErrorHandler = &StdHandler{}
2018-08-20 08:38:03 +00:00
// StdHandler Standard error handler
type StdHandler struct{}
2017-02-07 21:33:23 +00:00
func (e *StdHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, err error) {
statusCode := http.StatusInternalServerError
2018-08-20 08:38:03 +00:00
2017-02-07 21:33:23 +00:00
if e, ok := err.(net.Error); ok {
if e.Timeout() {
statusCode = http.StatusGatewayTimeout
} else {
statusCode = http.StatusBadGateway
}
} else if err == io.EOF {
statusCode = http.StatusBadGateway
2018-08-20 08:38:03 +00:00
} else if err == context.Canceled {
statusCode = StatusClientClosedRequest
2017-02-07 21:33:23 +00:00
}
2018-08-20 08:38:03 +00:00
2017-02-07 21:33:23 +00:00
w.WriteHeader(statusCode)
2018-08-20 08:38:03 +00:00
w.Write([]byte(statusText(statusCode)))
log.Debugf("'%d %s' caused by: %v", statusCode, statusText(statusCode), err)
}
func statusText(statusCode int) string {
if statusCode == StatusClientClosedRequest {
return StatusClientClosedRequestText
}
return http.StatusText(statusCode)
2017-02-07 21:33:23 +00:00
}
2018-08-20 08:38:03 +00:00
// ErrorHandlerFunc error handler function type
2017-02-07 21:33:23 +00:00
type ErrorHandlerFunc func(http.ResponseWriter, *http.Request, error)
// ServeHTTP calls f(w, r).
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, err error) {
f(w, r, err)
}