-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.go
64 lines (54 loc) · 1.27 KB
/
send.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
package response
import (
"net/http"
"github.com/yoas0bi/micro-toolkit/exception"
"github.com/yoas0bi/micro-toolkit/http/response"
"github.com/yoas0bi/micro-toolkit/logger/zap"
)
// Failed use to response error messge
func Failed(w *restful.Response, err error, opts ...response.Option) {
var (
errCode int
httpCode int
ns string
reason string
data interface{}
meta interface{}
)
switch t := err.(type) {
case exception.APIException:
errCode = t.ErrorCode()
reason = t.GetReason()
data = t.GetData()
meta = t.GetMeta()
ns = t.GetNamespace()
httpCode = t.GetHttpCode()
default:
errCode = exception.UnKnownException
}
if httpCode == 0 {
httpCode = http.StatusInternalServerError
}
resp := response.Data{
Code: &errCode,
Namespace: ns,
Reason: reason,
Message: err.Error(),
Data: data,
Meta: meta,
}
for _, opt := range opts {
opt.Apply(&resp)
}
err = w.WriteHeaderAndEntity(httpCode, resp)
if err != nil {
zap.L().Errorf("send failed response error, %s", err)
}
}
// Success use to response success data
func Success(w *restful.Response, data interface{}, opts ...response.Option) {
err := w.WriteEntity(data)
if err != nil {
zap.L().Errorf("send success response error, %s", err)
}
}