/
handler.go
111 lines (89 loc) · 2.28 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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package httphelper
import (
"crypto/rand"
"encoding/hex"
"net/http"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/juju/errgo"
"github.com/julienschmidt/httprouter"
"github.com/sebest/xff"
)
type Handler func(http.ResponseWriter, *http.Request, httprouter.Params) *HandlerError
type HandlerError struct {
Error error
Code int
}
func NewHandlerErrorDef(err error) *HandlerError {
return NewHandlerError(err, http.StatusInternalServerError)
}
func NewHandlerError(err error, code int) *HandlerError {
return &HandlerError{Error: err, Code: code}
}
func HandlerLoggerHTTP(fn Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if Stopping {
handlerLogger(PageRouterStopping, w, r, nil)
} else {
handlerLogger(fn, w, r, nil)
}
},
)
}
func HandlerLoggerRouter(fn Handler) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
if Stopping {
handlerLogger(PageRouterStopping, w, r, p)
} else {
handlerLogger(fn, w, r, p)
}
}
}
func NewHandlerLogEntry(r *http.Request) *log.Entry {
remoteAddr := xff.GetRemoteAddr(r)
entry := log.WithFields(log.Fields{
"context": "http",
"url": r.URL,
"remote": remoteAddr,
})
var err error
entry.Data["request_id"], err = generateID(16)
if err != nil {
panic("can not generate id for request")
}
return entry
}
func handlerLogger(fn Handler, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
l := NewHandlerLogEntry(r)
l.Debug("started handling request")
starttime := time.Now()
err := fn(w, r, p)
duration := time.Since(starttime)
l.Data["duration"] = duration
code := http.StatusOK
if err != nil {
code = err.Code
}
l.Data["status"] = code
l.Data["text_status"] = http.StatusText(code)
if err != nil {
if err.Error != nil {
l.Data["error_message"] = err.Error
l.Debug(errgo.Details(err.Error))
l.Error("completed handling request")
scode := strconv.Itoa(err.Code)
http.Error(w, scode+" ("+http.StatusText(err.Code)+") - "+err.Error.Error(), err.Code)
}
} else {
l.Info("completed handling request")
}
}
func generateID(n int) (string, error) {
r := make([]byte, n)
_, err := rand.Read(r)
if err != nil {
return "", err
}
return hex.EncodeToString(r), nil
}