-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
42 lines (35 loc) · 1.19 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package utils
import (
"io"
"net"
"net/http"
)
// ErrorHandler represents the error-specific interface required by error handlers.
type ErrorHandler interface {
ServeHTTP(w http.ResponseWriter, req *http.Request, err error)
}
// StdHandler is an empty struct.
type StdHandler struct{}
// ErrorHandlerFunc represents function interface for error handlers.
type ErrorHandlerFunc func(http.ResponseWriter, *http.Request, error)
// DefaultHandler stores the default error handled to be used, which is an no-op.
var DefaultHandler ErrorHandler = &StdHandler{}
// ServeHTTP replies with the proper status code based on the given error and writes the body.
func (e *StdHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, err error) {
statusCode := http.StatusInternalServerError
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
}
w.WriteHeader(statusCode)
w.Write([]byte(http.StatusText(statusCode)))
}
// ServeHTTP calls f(w, r).
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, err error) {
f(w, r, err)
}