-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathhttp_utils.go
49 lines (41 loc) · 969 Bytes
/
http_utils.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
package butlerd
import (
"log"
"net/http"
"github.com/pkg/errors"
)
type httpError struct {
code int
cause error
}
func (he *httpError) Error() string {
return he.cause.Error()
}
func HTTPError(code int, msg string, args ...interface{}) error {
err := errors.Errorf(msg, args...)
return &httpError{code: code, cause: err}
}
type CoolHandler func(w http.ResponseWriter, r *http.Request) error
func H(f CoolHandler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
if r := recover(); r != nil {
if rErr, ok := r.(error); ok {
log.Printf("Panic! %+v", errors.WithStack(rErr))
} else {
log.Printf("Panic! %+v", r)
}
http.Error(w, "Internal Error", 500)
}
}()
err := f(w, r)
if err != nil {
log.Printf("%+v", err)
if he, ok := errors.Cause(err).(*httpError); ok {
http.Error(w, he.cause.Error(), he.code)
} else {
http.Error(w, err.Error(), 500)
}
}
}
}