-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
64 lines (51 loc) · 1.28 KB
/
handler.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
package logger
import (
"net/http"
"strconv"
"github.com/go-playground/errors/v5"
)
// NewRequestLogger returns a middleware that logs the request and injects a Logger into
// the context. This Logger can be used during the life of the request, and all logs
// generated will be correlated to the request log.
//
// If not configured, request logs are sent to stderr by default.
func NewRequestLogger(e Exporter) func(http.Handler) http.Handler {
return e.Middleware()
}
// Exporter is the interface for implementing a middleware to export logs to some destination
type Exporter interface {
Middleware() func(http.Handler) http.Handler
}
func requestSize(length string) int64 {
l, err := strconv.Atoi(length)
if err != nil {
return 0
}
return int64(l)
}
type statusWriter struct {
http.ResponseWriter
status int
length int64
}
func (w *statusWriter) Status() int {
if w.status == 0 {
return http.StatusOK
}
return w.status
}
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func (w *statusWriter) Write(b []byte) (int, error) {
if w.status == 0 {
w.status = 200
}
n, err := w.ResponseWriter.Write(b)
w.length += int64(n)
if err != nil {
return n, errors.Wrap(err, "http.ResponseWriter.Write()")
}
return n, nil
}