-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmiddleware.go
More file actions
61 lines (57 loc) · 1.65 KB
/
middleware.go
File metadata and controls
61 lines (57 loc) · 1.65 KB
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
package httpx
import (
"context"
es "errors"
"strings"
"time"
"github.com/coffeehc/base/errors"
"github.com/coffeehc/base/log"
"github.com/gofiber/fiber/v3"
"go.uber.org/zap"
)
func AccessLogMiddleware() fiber.Handler {
return func(c fiber.Ctx) error {
t := time.Now()
e := c.Next()
if e == nil {
log.Debug(c.Path(), zap.Duration("times", time.Since(t)), zap.String("method", c.Method()))
} else {
log.Error("HTTP访问", zap.Duration("times", time.Since(t)), zap.String("mothod", c.Method()), zap.String("path", c.Path()), zap.Int("status", c.Response().StatusCode()))
}
return e
}
}
func RecoverMiddleware(t time.Duration) fiber.Handler {
return func(c fiber.Ctx) error {
timeoutContext, cancel := context.WithTimeout(c.Context(), t)
defer func() {
cancel()
if err := recover(); err != nil {
path := c.Path()
if errStr, ok := err.(string); ok {
log.DPanic(errStr, zap.String("method", c.Method()), zap.String("path", path))
} else {
e := errors.ConverUnknowError(err)
if errors.IsMessageError(e) {
log.Error(e.Error(), zap.String("method", c.Method()), zap.String("path", path))
} else {
if strings.HasPrefix(e.Error(), "context ") || strings.HasPrefix(e.Error(), "rpc error") {
log.Error(e.Error(), zap.String("method", c.Method()), zap.String("path", path))
} else {
log.DPanic(e.Error(), zap.String("method", c.Method()), zap.String("path", path))
}
}
}
c.SendStatus(500)
}
}()
c.SetContext(timeoutContext)
err := c.Next()
if err != nil {
if es.Is(err, context.DeadlineExceeded) {
return fiber.ErrRequestTimeout
}
}
return err
}
}