forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmw.go
90 lines (78 loc) · 2.11 KB
/
mw.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
package gserv
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync/atomic"
"time"
"github.com/gorilla/securecookie"
"github.com/alpineiq/gserv/internal"
)
var reqID uint64
// LogRequests is a request logger middleware.
// If logJSONRequests is true, it'll attempt to parse the incoming request's body and output it to the log.
func LogRequests(logJSONRequests bool) Handler {
return func(ctx *Context) Response {
var (
req = ctx.Req
url = req.URL
start = time.Now()
id = atomic.AddUint64(&reqID, 1)
extra string
)
if logJSONRequests {
switch m := req.Method; m {
case http.MethodPost, http.MethodPut, http.MethodPatch:
var buf bytes.Buffer
io.Copy(&buf, req.Body)
req.Body.Close()
req.Body = ioutil.NopCloser(&buf)
j, _ := internal.Marshal(req.Header)
if ln := buf.Len(); ln > 0 {
switch buf.Bytes()[0] {
case '[', '{', 'n': // [], {} and nullable
extra = fmt.Sprintf("\n\tHeaders: %s\n\tRequest (%d): %s", j, ln, buf.String())
default:
extra = fmt.Sprintf("\n\tHeaders: %s\n\tRequest (%d): <binary>", j, buf.Len())
}
}
}
}
ctx.NextMiddleware()
ctx.Next()
ct := req.Header.Get("Content-Type")
switch ct {
case MimeJSON:
ct = "[JSON] "
case MimeMsgPack:
ct = "[MSGP] "
case MimeEvent:
ct = "[SSE] "
case "":
default:
ct = "[" + ct + "] "
}
ctx.LogSkipf(1, "[reqID:%05d] [%s] [%s] %s[%d] %s %s [%s]%s",
id, ctx.ClientIP(), req.UserAgent(), ct, ctx.Status(), req.Method, url.Path, time.Since(start), extra)
return nil
}
}
const secureCookieKey = ":SC:"
// SecureCookie is a middleware to enable SecureCookies.
// For more details check `go doc securecookie.New`
func SecureCookie(hashKey, blockKey []byte) Handler {
return func(ctx *Context) Response {
ctx.Set(secureCookieKey, securecookie.New(hashKey, blockKey))
return nil
}
}
// GetSecureCookie returns the *securecookie.SecureCookie associated with the Context, or nil.
func GetSecureCookie(ctx *Context) *securecookie.SecureCookie {
sc, ok := ctx.Get(secureCookieKey).(*securecookie.SecureCookie)
if ok {
return sc
}
return nil
}