-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
87 lines (76 loc) · 1.94 KB
/
response.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 app
import (
"context"
"encoding/hex"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
oteltrace "go.opentelemetry.io/otel/trace"
"strconv"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
TraceID string `json:"trace_id"`
}
const (
RELOGIN = 1
ERROR = 7
SUCCESS = 0
)
func Result(c context.Context,
ctx *app.RequestContext,
code int,
data interface{}, msg string) {
traceID := oteltrace.SpanContextFromContext(c).TraceID().String()
if data == nil {
ctx.JSON(consts.StatusOK, utils.H{
"code": code,
"msg": msg,
"trace_id": traceID,
})
} else {
ctx.JSON(consts.StatusOK, Response{
code,
msg,
data,
traceID,
})
}
ctx.Abort()
}
func Ok(c context.Context,
ctx *app.RequestContext) {
Result(c, ctx, SUCCESS, nil, "操作成功")
}
func OkWithMessage(c context.Context,
ctx *app.RequestContext, msg string) {
Result(c, ctx, SUCCESS, nil, msg)
}
func OkWithData(c context.Context,
ctx *app.RequestContext, data interface{}) {
Result(c, ctx, SUCCESS, data, "操作成功")
}
func OkWithDetailed(c context.Context,
ctx *app.RequestContext, data interface{}, message string) {
Result(c, ctx, SUCCESS, data, message)
}
func Fail(c context.Context,
ctx *app.RequestContext) {
Result(c, ctx, ERROR, nil, "操作失败")
}
func FailWithMessage(c context.Context,
ctx *app.RequestContext, message string) {
Result(c, ctx, ERROR, nil, message)
}
func ReLoginWithMessage(c context.Context,
ctx *app.RequestContext, message string) {
Result(c, ctx, RELOGIN, nil, message)
}
func OkWithBody(data []byte, ctx *app.RequestContext, bodyLength int) {
dst := make([]byte, hex.EncodedLen(len(data)))
hex.Encode(dst, data)
ctx.Header("X-Body-Length", strconv.Itoa(bodyLength))
ctx.Data(consts.StatusOK, "application/json; charset=UTF-8", dst)
}