-
-
Notifications
You must be signed in to change notification settings - Fork 121
/
resp.go
83 lines (66 loc) · 1.75 KB
/
resp.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
package common
import (
"net/http"
"github.com/ArtalkJS/Artalk/internal/log"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
// JSONResult JSON Response data structure
type JSONResult struct {
Msg string `json:"msg,omitempty"` // Message
Data interface{} `json:"data,omitempty"` // Data
}
// RespData is just response data
func RespData(c *fiber.Ctx, data interface{}) error {
return c.Status(http.StatusOK).JSON(data)
}
// RespSuccess is just response success
func RespSuccess(c *fiber.Ctx, msg ...string) error {
respData := &JSONResult{
Msg: "Success",
}
// Optional msg parameter
if len(msg) > 0 {
respData.Msg = msg[0]
}
return c.Status(http.StatusOK).JSON(respData)
}
// RespError is just response error
func RespError(c *fiber.Ctx, code int, msg string, data ...Map) error {
respData := Map{}
if len(data) > 0 {
respData = data[0]
}
respData["msg"] = msg
c.Status(code)
LogWithHttpInfo(c, func(l *zap.SugaredLogger) {
l.Error(msg)
})
return c.JSON(respData)
}
func LogWithHttpInfo(c *fiber.Ctx, logFn func(l *zap.SugaredLogger)) {
path := string(c.Request().URI().Path())
if path == "" {
path = "/"
}
id := c.Get(fiber.HeaderXRequestID)
if id == "" {
id = c.GetRespHeader(fiber.HeaderXRequestID)
}
logger := log.StandardLogger().Sugar().With(
"id", id,
"path", path,
"method", c.Method(),
"ip", c.IP(),
"remote_addr", c.Context().RemoteAddr().String(),
"host", string(c.Request().Host()),
"referer", string(c.Request().Header.Referer()),
"user_agent", string(c.Request().Header.UserAgent()),
"status", c.Response().StatusCode(),
// "headers", req.Header,
)
var skipper = func(l *zap.SugaredLogger) *zap.SugaredLogger {
return l.WithOptions(zap.AddCallerSkip(2))
}
logFn(skipper(logger))
}