-
Notifications
You must be signed in to change notification settings - Fork 88
/
middleware.go
109 lines (91 loc) · 2.46 KB
/
middleware.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
package handlers
import (
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/session"
"github.com/replicatedhq/kots/pkg/store"
)
type loggingResponseWriter struct {
http.ResponseWriter
StatusCode int
}
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{w, http.StatusOK}
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.StatusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func CorsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if handleOptionsRequest(w, r) {
return
}
next.ServeHTTP(w, r)
})
}
func DebugLoggingMiddleware(next http.Handler) http.Handler {
if os.Getenv("DEBUG") != "true" {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
lrw := NewLoggingResponseWriter(w)
next.ServeHTTP(lrw, r)
logger.Debugf(
"method=%s status=%d duration=%s request=%s",
r.Method,
lrw.StatusCode,
time.Since(startTime).String(),
r.RequestURI,
)
})
}
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
lrw := NewLoggingResponseWriter(w)
next.ServeHTTP(lrw, r)
if os.Getenv("DEBUG") != "true" && lrw.StatusCode < http.StatusBadRequest {
return
}
logger.Infof(
"method=%s status=%d duration=%s request=%s",
r.Method,
lrw.StatusCode,
time.Since(startTime).String(),
r.RequestURI,
)
})
}
func RequireValidSessionMiddleware(kotsStore store.Store) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess, err := requireValidSession(kotsStore, w, r)
if err != nil {
if !kotsStore.IsNotFound(err) {
logger.Error(errors.Wrapf(err, "request %q", r.RequestURI))
}
return
}
r = session.ContextSetSession(r, sess)
next.ServeHTTP(w, r)
})
}
}
func RequireValidSessionQuietMiddleware(kotsStore store.Store) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sess, err := requireValidSession(kotsStore, w, r)
if err != nil {
return
}
r = session.ContextSetSession(r, sess)
next.ServeHTTP(w, r)
})
}
}