This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
80 lines (66 loc) · 2.18 KB
/
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
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
package core
import "errors"
import "encoding/json"
import "net/http"
import log "github.com/sirupsen/logrus"
type HttpError struct {
Error error
Status int
Code int
}
func NewHttpError(pErr error, pStatus int, pCode int) HttpError {
return HttpError{pErr, pStatus, pCode}
}
func WriteJson(pWriter http.ResponseWriter, pObj interface{}) {
lVal, _ := json.Marshal(pObj)
pWriter.Header().Set("Content-Type", "application/json")
pWriter.Write(lVal)
}
func WriteJsonError(pWriter http.ResponseWriter, pStatus int, pCode int, pErr error) {
lErr := struct {
Code int `json:"code"`
Error string `json:"error"`
}{ pCode, pErr.Error() }
lVal, _ := json.Marshal(lErr)
pWriter.Header().Set("Content-Type", "application/json")
pWriter.WriteHeader(pStatus)
pWriter.Write(lVal)
}
func HandlePanic(pRes http.ResponseWriter, pReq *http.Request) {
switch lErr := recover().(type) {
case nil:
case HttpError:
WriteJsonError(pRes, lErr.Status, lErr.Code, lErr.Error)
default:
WriteJsonError(pRes, 500, 20, errors.New("undefined panic type"))
}
}
func DecorateHandler(pFunc func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
lReq := WrapHandler(LogRequestHandler, pFunc)
lRes := WrapHandler(lReq, LogResponseHandler)
lProtect := WrapDefer(lRes, HandlePanic)
return lProtect
}
func LogRequestHandler(pRes http.ResponseWriter, pReq *http.Request) {
log.WithFields(log.Fields{
"method": pReq.Method,
"host": pReq.Host,
"client": pReq.RemoteAddr,
"path": pReq.RequestURI,
"headers": pReq.Header,
}).Info("handling http request")
}
func LogResponseHandler(pRes http.ResponseWriter, pReq *http.Request) {
}
func WrapHandler(pDecorator func(http.ResponseWriter, *http.Request), pFunc func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(pRes http.ResponseWriter, pReq *http.Request) {
pDecorator(pRes, pReq)
pFunc(pRes, pReq)
}
}
func WrapDefer(pFunc func(http.ResponseWriter, *http.Request), pDefer func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
return func(pRes http.ResponseWriter, pReq *http.Request) {
defer pDefer(pRes, pReq)
pFunc(pRes, pReq)
}
}