-
Notifications
You must be signed in to change notification settings - Fork 0
/
httperror.go
84 lines (68 loc) · 1.75 KB
/
httperror.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package webutil
import (
"errors"
"fmt"
"net/http"
"os"
)
type serverError struct {
e error
}
type HttpError int
func HttpErrorHandler(code int) http.Handler {
return HttpError(code)
}
func (e HttpError) Error() string {
return fmt.Sprintf("HTTP error %d", e)
}
func (e HttpError) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
if e == http.StatusUnauthorized {
w.Header().Set("WWW-Authenticate", "Basic realm=\"Website Access\"")
}
w.WriteHeader(int(e))
fmt.Fprintf(w, "HTTP Error code %d: %s", int(e), http.StatusText(int(e)))
}
func (e *serverError) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
switch e.e {
case os.ErrNotExist:
http.NotFound(w, req)
default:
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Server error: %s", e.e)
}
}
// HTTPStatus returns the value set in http error
func (e HttpError) HTTPStatus() int {
return int(e)
}
func ErrorToHttpHandler(e error) http.Handler {
if h, ok := e.(http.Handler); ok {
return h
}
return &serverError{e}
}
type handlerError struct {
h http.Handler
}
func HttpHandlerToError(h http.Handler) error {
return &handlerError{h}
}
func (h *handlerError) Error() string {
return "request is being forwarded"
}
func (h *handlerError) ServeHTTP(w http.ResponseWriter, req *http.Request) {
h.h.ServeHTTP(w, req)
}
func ServeError(w http.ResponseWriter, req *http.Request, err error) {
var h http.Handler
if errors.As(err, &h) {
h.ServeHTTP(w, req)
return
}
// fallback to instance of serverError
(&serverError{err}).ServeHTTP(w, req)
}