-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
172 lines (149 loc) · 4.68 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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package Jgrpc_response
import (
"context"
"encoding/json"
"log"
"net/http"
"reflect"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var (
defaultMsg = "操作成功"
)
type defaultData struct{}
// Response Http 服务返回的结构体
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
}
// CustomMarshaller Custom marshaller
type CustomMarshaller struct{ runtime.JSONPb }
// Marshal Custom marshal
func (m *CustomMarshaller) Marshal(v interface{}) ([]byte, error) { return nil, nil }
// HttpErrorHandler Http service error handler
func HttpErrorHandler(ctx context.Context, mux *runtime.ServeMux, m runtime.Marshaler, w http.ResponseWriter, req *http.Request, err error) {
r := &Response{
Code: HTTPStatusFromCode(status.Convert(err).Code()),
Msg: status.Convert(err).Proto().GetMessage(),
}
// 判断返回的 details 是否为空,如果是,则设置成空的结构体对象
if status.Convert(err).Proto().GetDetails() == nil {
r.Data = &defaultData{}
} else {
r.Data = status.Convert(err).Proto().GetDetails()
}
// 转译成返回 http 请求的 json 数据格式
jsonStr, err := json.Marshal(r)
if err != nil {
log.Println("系统错误,错误信息:" + err.Error())
r.Response(http.StatusInternalServerError, w, "系统错误")
return
}
r.Response(r.Code, w, string(jsonStr))
}
// HttpSuccessResponseModifier Request successful return data format
func HttpSuccessResponseModifier(ctx context.Context, w http.ResponseWriter, pbMsg proto.Message) error {
r := &Response{}
b, err := protojson.Marshal(pbMsg)
if err != nil {
log.Println("系统错误,错误信息:" + err.Error())
r.Response(http.StatusInternalServerError, w, "系统错误")
return nil
}
respByte := []byte(`{"code":200,"msg":"` + defaultMsg + `","data":` + string(b) + `}`)
r.Response(http.StatusOK, w, string(respByte))
return nil
}
// Response Method for handling returned http api requests.
// In json format, and other errors are specified by the parameter Code.
func (r *Response) Response(httpStatus int, w http.ResponseWriter, response string) {
w.WriteHeader(httpStatus)
r.write(w.Write, []byte(response))
}
// write Logging write errors
func (*Response) write(write func([]byte) (int, error), body []byte) {
_, err := write(body)
if err != nil {
log.Printf("http response write failed: %v", err)
}
}
// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status.
// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
func HTTPStatusFromCode(code codes.Code) int {
switch code {
case codes.OK:
return http.StatusOK
case codes.Canceled:
return 499
case codes.Unknown:
return http.StatusInternalServerError
case codes.InvalidArgument:
return http.StatusBadRequest
case codes.DeadlineExceeded:
return http.StatusGatewayTimeout
case codes.NotFound:
return http.StatusNotFound
case codes.AlreadyExists:
return http.StatusConflict
case codes.PermissionDenied:
return http.StatusForbidden
case codes.Unauthenticated:
return http.StatusUnauthorized
case codes.ResourceExhausted:
return http.StatusTooManyRequests
case codes.FailedPrecondition:
// Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status.
return http.StatusBadRequest
case codes.Aborted:
return http.StatusConflict
case codes.OutOfRange:
return http.StatusBadRequest
case codes.Unimplemented:
return http.StatusNotImplemented
case codes.Internal:
return http.StatusInternalServerError
case codes.Unavailable:
return http.StatusServiceUnavailable
case codes.DataLoss:
return http.StatusInternalServerError
default:
grpclog.Infof("Unknown gRPC error code: %v", code)
return http.StatusInternalServerError
}
}
// MarshalJSON 格式化当请求成功时,只有一个 response 结构体
func (r *Response) MarshalJSON() ([]byte, error) {
mm := runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
},
}
buf := []byte("{")
st := reflect.TypeOf(*r)
vt := reflect.ValueOf(*r)
for i := 0; i < st.NumField(); i++ {
if i != 0 {
buf = append(buf, ',')
}
field := st.Field(i)
tag := field.Tag.Get("json")
buf = append(buf, []byte("\""+tag+"\": ")...)
value := vt.Field(i).Interface()
var vBuf []byte
if tag == "data" {
vBuf, _ = mm.Marshal(r.Data)
} else {
vBuf, _ = json.Marshal(value)
}
buf = append(buf, vBuf...)
}
end := []byte{'}'}
buf = append(buf, end...)
return buf, nil
}