-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrap.go
87 lines (75 loc) · 1.92 KB
/
wrap.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
package requestlog
import (
"io"
"net/http"
"os"
"regexp"
"text/template"
"time"
"github.com/andrew-d/go-termutil"
"github.com/jpillora/ansi"
"github.com/jpillora/sizestr"
)
func init() {
sizestr.LowerCase()
}
type Colors struct {
Grey, Green, Cyan, Yellow, Red, Reset string
}
var basicColors = &Colors{string(ansi.ResetBytes), string(ansi.GreenBytes), string(ansi.CyanBytes), string(ansi.YellowBytes), string(ansi.YellowBytes), string(ansi.ResetBytes)}
var noColors = &Colors{} //no colors
type Options struct {
Writer io.Writer
TimeFormat string
Format string
formatTmpl *template.Template
Colors *Colors
}
var DefaultOptions = Options{
Writer: os.Stdout,
TimeFormat: "2006/01/02 15:04:05.000",
Format: `{{ if .Timestamp }}{{ .Timestamp }} {{end}}` +
`{{ .Method }} {{ .Path }} {{ .CodeColor }}{{ .Code }}{{ .Reset }} ` +
`{{ .Duration }}{{ if .Size }} {{ .Size }}{{end}}` +
`{{ if .IP }} ({{ .IP }}){{end}}` + "\n",
Colors: defaultColors(),
}
func defaultColors() *Colors {
sizestr.ToggleCase()
if termutil.Isatty(os.Stdout.Fd()) {
return basicColors
} else {
return noColors
}
}
func Wrap(next http.Handler) http.Handler {
return WrapWith(next, Options{})
}
func WrapWith(next http.Handler, opts Options) http.Handler {
if opts.Writer == nil {
opts.Writer = DefaultOptions.Writer
}
if opts.TimeFormat == "" {
opts.TimeFormat = DefaultOptions.TimeFormat
}
if opts.Format == "" {
opts.Format = DefaultOptions.Format
}
if opts.Colors == nil {
opts.Colors = DefaultOptions.Colors
}
var err error
opts.formatTmpl, err = template.New("format").Parse(opts.Format)
if err != nil {
panic(err)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := monitorWriter(w, r, &opts)
next.ServeHTTP(m, r)
m.Log()
})
}
var fmtDurationRe = regexp.MustCompile(`\.\d+`)
func fmtDuration(t time.Duration) string {
return fmtDurationRe.ReplaceAllString(t.String(), "")
}