-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
57 lines (46 loc) · 960 Bytes
/
main.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
package main
import (
"github.com/exuan/gin-wrap-handler/errors"
"github.com/gin-gonic/gin"
"net/http"
)
type Ret struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func wrap(f func(c *gin.Context) (interface{}, error)) gin.HandlerFunc {
return func(c *gin.Context) {
res, err := f(c)
// if nil, then return ''
if res == nil {
res = ``
}
ret := Ret{
Data: res,
}
code := http.StatusOK
if err != nil {
e := errors.FromError(err)
// wrap http status code
if e.Code > 0 && e.Code <= 600 {
code = e.Code
}
ret.Msg = e.Msg
ret.Code = e.Code
}
c.JSON(code, ret)
}
}
func main() {
r := gin.Default()
r.GET("/", wrap(welcome))
r.GET("/err", wrap(err))
r.Run()
}
func welcome(c *gin.Context) (interface{}, error) {
return nil, nil
}
func err(c *gin.Context) (interface{}, error) {
return nil, errors.New(http.StatusBadRequest, "bad request")
}