forked from gomods/athens
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
49 lines (43 loc) · 1.17 KB
/
request.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
package middleware
import (
"fmt"
"net/http"
"github.com/fatih/color"
"github.com/gomods/athens/pkg/log"
logrus "github.com/sirupsen/logrus"
)
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(statusCode int) {
rw.statusCode = statusCode
rw.ResponseWriter.WriteHeader(statusCode)
}
// RequestLogger logs request params to standard output
// it should only be used during dev.
func RequestLogger(h http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
rw := &responseWriter{w, 0}
h.ServeHTTP(rw, r)
log.EntryFromContext(r.Context()).WithFields(logrus.Fields{
"http-status": fmtResponseCode(rw.statusCode),
}).Infof("incoming request")
}
return http.HandlerFunc(f)
}
func fmtResponseCode(statusCode int) string {
if statusCode == 0 {
statusCode = 200
}
status := fmt.Sprint(statusCode)
switch {
case statusCode < http.StatusBadRequest:
status = color.GreenString("%v", status)
case statusCode >= http.StatusBadRequest && statusCode < http.StatusInternalServerError:
status = color.HiYellowString("%v", status)
default:
status = color.HiRedString("%v", status)
}
return status
}