forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filter.go
90 lines (73 loc) · 2.15 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package audit
import (
"bufio"
"bytes"
"context"
"fmt"
"net"
"net/http"
"reflect"
"github.com/rancher/rancher/pkg/auth/util"
"github.com/sirupsen/logrus"
)
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, fmt.Errorf("Upstream ResponseWriter of type %v does not implement http.Hijacker", reflect.TypeOf(aw.ResponseWriter))
}
func (aw *wrapWriter) CloseNotify() <-chan bool {
if cn, ok := aw.ResponseWriter.(http.CloseNotifier); ok {
return cn.CloseNotify()
}
logrus.Errorf("Upstream ResponseWriter of type %v does not implement http.CloseNotifier", reflect.TypeOf(aw.ResponseWriter))
return make(<-chan bool)
}
func (aw *wrapWriter) Flush() {
if f, ok := aw.ResponseWriter.(http.Flusher); ok {
f.Flush()
return
}
logrus.Errorf("Upstream ResponseWriter of type %v does not implement http.Flusher", reflect.TypeOf(aw.ResponseWriter))
}