-
Notifications
You must be signed in to change notification settings - Fork 0
/
filter.go
71 lines (57 loc) · 1.55 KB
/
filter.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
package audit
import (
"bufio"
"bytes"
"context"
"errors"
"net"
"net/http"
"github.com/rancher/rancher/pkg/auth/util"
)
func NewAuditLogFilter(ctx context.Context, auditWriter *LogWriter, next http.Handler) http.Handler {
return &auditHandler{
next: next,
auditWriter: auditWriter,
}
}
type auditHandler struct {
next http.Handler
auditWriter *LogWriter
}
func (h auditHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if h.auditWriter == nil {
h.next.ServeHTTP(rw, req)
return
}
user := GetUserInfo(req)
context := context.WithValue(req.Context(), userKey, user)
req = req.WithContext(context)
auditLog, err := new(h.auditWriter, req)
if err != nil {
util.ReturnHTTPError(rw, req, 500, err.Error())
return
}
wr := &wrapWriter{ResponseWriter: rw, auditWriter: h.auditWriter, statusCode: http.StatusOK}
h.next.ServeHTTP(wr, req)
auditLog.write(user, req.Header, wr.Header(), wr.statusCode, wr.buf.Bytes())
}
type wrapWriter struct {
http.ResponseWriter
auditWriter *LogWriter
statusCode int
buf bytes.Buffer
}
func (aw *wrapWriter) WriteHeader(statusCode int) {
aw.ResponseWriter.WriteHeader(statusCode)
aw.statusCode = statusCode
}
func (aw *wrapWriter) Write(body []byte) (int, error) {
aw.buf.Write(body)
return aw.ResponseWriter.Write(body)
}
func (aw *wrapWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := aw.ResponseWriter.(http.Hijacker); ok {
return hijacker.Hijack()
}
return nil, nil, errors.New("the ResponseWriter doesn't support the Hijacker interface")
}