-
Notifications
You must be signed in to change notification settings - Fork 0
/
fiber.go
70 lines (60 loc) · 1.38 KB
/
fiber.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
package logger
import (
"fmt"
"github.com/gofiber/fiber/v2"
"time"
)
var DefaultConfigFiber = ConfigFiber{
SkipperFiber: DefaultSkipperFiber,
}
func FiberMiddleware(config ConfigFiber) fiber.Handler {
if config.SkipperFiber == nil {
config.SkipperFiber = DefaultSkipperFiber
}
return func(ctx *fiber.Ctx) error {
logger := New(WithFormatter(&JSONFormatter{}))
if config.SkipperFiber(ctx) {
return ctx.Next()
}
if config.BeforeFuncFiber != nil {
config.BeforeFuncFiber(ctx)
}
var (
clientIP = ctx.IP()
method = ctx.Method()
userAgent = string(ctx.Request().Header.UserAgent())
uri = string(ctx.Request().Header.RequestURI())
errs string
start = time.Now()
isError bool
)
logger.WithFields(map[string]interface{}{
ClientIPField: clientIP,
RequestMethodField: method,
UserAgentField: userAgent,
URIField: uri,
})
ctx.Context().SetUserValue(Key, logger)
err := ctx.Next()
var (
statusCode = ctx.Response().StatusCode()
)
logger.WithField(StatusField, statusCode)
if err != nil {
isError = true
errs = err.Error()
}
if len(errs) > 0 {
logger.WithField(ErrorsField, errs)
}
end := time.Now()
logger.WithField(EndField, end)
msg := fmt.Sprintf("latency: %v", end.Sub(start))
if isError {
logger.Error(msg)
} else {
logger.Info(msg)
}
return err
}
}