/
util.go
122 lines (110 loc) · 2.42 KB
/
util.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package protocol
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/wuranxu/library/auth"
"google.golang.org/grpc/metadata"
)
var (
UserInfoNotFound = errors.New("未获取到用户信息")
UserInfoParseError = errors.New("用户信息解析失败")
DecodeError = "解析返回数据失败"
)
func Success(data ...interface{}) *Response {
res := &Response{Code: 0, Msg: "操作成功"}
if len(data) > 0 {
bt, err := json.Marshal(data[0])
if err != nil {
res.Msg = err.Error()
res.Code = 101
return res
}
res.ResultJson = bt
}
return res
}
func SuccessWithMsg(msg string, data ...interface{}) *Response {
res := Success(data...)
res.Msg = msg
return res
}
func Error(code int32, msg interface{}, data ...interface{}) *Response {
r := new(Response)
return r.Build(code, msg, data...)
}
func (m *Response) Build(code int32, msg interface{}, data ...interface{}) *Response {
m.Code = code
if msg != nil {
switch msg.(type) {
case string:
m.Msg = msg.(string)
case error:
m.Msg = msg.(error).Error()
default:
m.Msg = fmt.Sprintf("%v", msg)
}
}
if len(data) > 0 {
bt, err := json.Marshal(data[0])
if err != nil {
m.Msg = err.Error()
}
m.ResultJson = bt
}
return m
}
func Unmarshal(in *Request, data interface{}) error {
if err := json.Unmarshal(in.RequestJson, data); err != nil {
return err
}
return nil
}
func MarshalRequest(data interface{}) (*Request, error) {
in := new(Request)
result, err := json.Marshal(data)
if err != nil {
return nil, err
}
in.RequestJson = result
return in, nil
}
func Marshal(out *Response, data interface{}) {
bt, err := json.Marshal(data)
if err != nil {
out.ResultJson = nil
out.Msg = DecodeError
return
}
out.ResultJson = bt
}
func GetHeader(ctx context.Context) map[string][]string {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil
}
return md
}
func GetHeaderKey(ctx context.Context, key string) string {
md, ok := metadata.FromIncomingContext(ctx)
if ok {
if get := md.Get(key); len(get) > 0 {
return get[0]
}
}
return ""
}
func FetchUserInfo(ctx context.Context) (*auth.CustomClaims, error) {
headers := GetHeader(ctx)
if result, ok := headers["user"]; ok {
if len(result) > 0 {
var claims auth.CustomClaims
if err := json.Unmarshal([]byte(result[0]), &claims); err != nil {
return nil, UserInfoParseError
}
return &claims, nil
}
}
return nil, UserInfoNotFound
}