This repository has been archived by the owner on Feb 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler.go
74 lines (60 loc) · 1.84 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
65
66
67
68
69
70
71
72
73
74
package log
import (
"fmt"
"log"
"time"
"github.com/volatile/core"
"github.com/volatile/core/httputil"
"github.com/whitedevops/colors"
)
// Use adds the handler to the default handlers stack.
// It prints each request/response information (time, duration, status, method, path).
func Use() {
core.BeforeRun(func() {
fmt.Printf("%s%s Server running on %s%s%s %s %s\n\n", colors.ResetAll, colors.Reverse, colors.ResetAll, colors.BackgroundMagenta, colors.White, core.Address, colors.ResetAll)
})
core.Use(func(c *core.Context) {
start := time.Now()
path := c.Request.URL.Path // Keep original request path in case of http.StripPrefix.
defer func() {
log.Printf(" %s %s %s %s", fmtDuration(start), fmtStatus(c), fmtMethod(c), fmtPath(path))
}()
defer c.Recover()
c.Next()
})
}
func fmtDuration(start time.Time) string {
return fmt.Sprintf("%s%s%13s%s", colors.ResetAll, colors.Dim, time.Since(start), colors.ResetAll)
}
func fmtStatus(c *core.Context) string {
code := httputil.ResponseStatus(c.ResponseWriter)
color := colors.White
switch {
case code >= 200 && code <= 299:
color += colors.BackgroundGreen
case code >= 300 && code <= 399:
color += colors.BackgroundCyan
case code >= 400 && code <= 499:
color += colors.BackgroundYellow
default:
color += colors.BackgroundRed
}
return fmt.Sprintf("%s%s %3d %s", colors.ResetAll, color, code, colors.ResetAll)
}
func fmtMethod(c *core.Context) string {
var color string
switch c.Request.Method {
case "GET":
color += colors.Green
case "POST":
color += colors.Cyan
case "PUT", "PATCH":
color += colors.Blue
case "DELETE":
color += colors.Red
}
return fmt.Sprintf("%s%s%s%s", colors.ResetAll, color, c.Request.Method, colors.ResetAll)
}
func fmtPath(path string) string {
return fmt.Sprintf("%s%s%s%s", colors.ResetAll, colors.Dim, path, colors.ResetAll)
}