forked from traefik/traefik
-
Notifications
You must be signed in to change notification settings - Fork 0
/
save_username.go
60 lines (47 loc) · 1.4 KB
/
save_username.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
package accesslog
import (
"context"
"net/http"
"github.com/urfave/negroni"
)
const (
clientUsernameKey key = "ClientUsername"
)
// SaveUsername sends the Username name to the access logger.
type SaveUsername struct {
next http.Handler
}
// NewSaveUsername creates a SaveUsername handler.
func NewSaveUsername(next http.Handler) http.Handler {
return &SaveUsername{next}
}
func (sf *SaveUsername) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
serveSaveUsername(r, func() {
sf.next.ServeHTTP(rw, r)
})
}
// SaveNegroniUsername adds the Username to the access logger data table.
type SaveNegroniUsername struct {
next negroni.Handler
}
// NewSaveNegroniUsername creates a SaveNegroniUsername handler.
func NewSaveNegroniUsername(next negroni.Handler) negroni.Handler {
return &SaveNegroniUsername{next}
}
func (sf *SaveNegroniUsername) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
serveSaveUsername(r, func() {
sf.next.ServeHTTP(rw, r, next)
})
}
func serveSaveUsername(r *http.Request, apply func()) {
table := GetLogDataTable(r)
username, ok := r.Context().Value(clientUsernameKey).(string)
if ok {
table.Core[ClientUsername] = username
}
apply()
}
// WithUserName adds a username to a requests' context
func WithUserName(req *http.Request, username string) *http.Request {
return req.WithContext(context.WithValue(req.Context(), clientUsernameKey, username))
}