-
Notifications
You must be signed in to change notification settings - Fork 51
/
error_handler.go
59 lines (47 loc) · 1.59 KB
/
error_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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package httpproxy
import (
"context"
"io"
"net"
"net/http"
)
const (
// TriremeBadGatewayText is the message to send when downstream fails.
TriremeBadGatewayText = ":The downstream port cannot be accessed. Please validate your service ports and address/hosts configuration"
// TriremeGatewayTimeout is the message to send when downstream times-out.
TriremeGatewayTimeout = ":The downstream node timed-out."
// StatusClientClosedRequest non-standard HTTP status code for client disconnection
StatusClientClosedRequest = 499
// StatusClientClosedRequestText non-standard HTTP status for client disconnection
StatusClientClosedRequestText = "Client Closed Request"
)
// TriremeHTTPErrHandler Standard error handler
type TriremeHTTPErrHandler struct{}
func (e TriremeHTTPErrHandler) 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
} else if err == context.Canceled {
statusCode = StatusClientClosedRequest
}
w.WriteHeader(statusCode)
w.Write([]byte(statusText(statusCode))) // nolint errcheck
}
func statusText(statusCode int) string {
prefix := http.StatusText(statusCode)
switch statusCode {
case http.StatusGatewayTimeout:
return prefix + TriremeGatewayTimeout
case http.StatusBadGateway:
return prefix + TriremeBadGatewayText
case StatusClientClosedRequest:
return StatusClientClosedRequestText
}
return prefix
}