-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
60 lines (51 loc) · 1.36 KB
/
common.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
package echotool
import (
"net/http"
"github.com/labstack/echo/v4"
)
type CommonResponse struct {
RequestID string `json:"request_id,omitempty"`
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
func RespOK(id string, code int, data interface{}) *CommonResponse {
return &CommonResponse{
RequestID: id,
Code: code,
Message: CodeMsg(code),
Data: data,
}
}
func RespError(id string, code int, err error) *CommonResponse {
resp := &CommonResponse{
RequestID: id,
Code: code,
Message: CodeMsg(code),
}
if err != nil {
resp.Message += " - " + err.Error()
}
return resp
}
func FinishWithCodeData(c echo.Context, code int, data interface{}) {
status := HTTPStatus(code)
if status < http.StatusMultipleChoices || status > http.StatusPermanentRedirect {
c.JSON(status, RespOK(GetRequestID(c), code, data))
} else {
c.Redirect(status, data.(string))
}
}
func AbortWithCodeErr(c echo.Context, code int, err error) {
c.JSON(HTTPStatus(code), RespError(GetRequestID(c), code, err))
}
func GetCommonFinisher() HandlerFunc {
return func(c echo.Context, ec *Context) {
FinishWithCodeData(c, ec.GetCode(), ec.GetData())
}
}
func GetCommonAborter() HandlerFunc {
return func(c echo.Context, ec *Context) {
AbortWithCodeErr(c, ec.GetCode(), ec.GetError())
}
}