-
Notifications
You must be signed in to change notification settings - Fork 7
/
router.go
108 lines (86 loc) · 2.44 KB
/
router.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
package gin
import (
"net/http"
"github.com/better-go/pkg/errors"
"github.com/better-go/pkg/log"
"github.com/gin-gonic/gin"
microErr "github.com/micro/go-micro/v2/errors"
)
/*
路由自动校验入参 + 格式化返回值
usage:
func userRegister(ctx *gin.Context) {
var req api.UserRegisterReq
ApiHandlerWrap(ctx, &req, func(ctx *gin.Context, in interface{}) (out interface{}, err error) {
// assert:
r, ok := in.(*api.UserRegisterReq)
if !ok {
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
}
return gs.Register(ctx, r)
})
}
*/
// apiHandlerFunc api logic func
type apiHandlerFunc func(ctx *gin.Context, in interface{}) (out interface{}, err error)
// ApiHandlerWrap 路由自动校验入参 + 格式化返回值
func ApiHandlerWrap(ctx *gin.Context, req interface{}, handlerFn apiHandlerFunc) {
log.Debugf("http api request entry: req=%+v", req)
//value := reflect.ValueOf(req)
//log.Debugf("req type before bind: %+v, type:%v", req, value.Type())
// validate req:
if err := ctx.ShouldBind(req); err != nil {
log.Error("invalid request params: %v", err)
ctx.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}
//value = reflect.ValueOf(req)
//log.Debugf("req type after bind: %+v, type:%v", req, value.Type())
//////////////////////////////////////////////////////////////////////////
//
// do api handler
//
resp, err := handlerFn(ctx, req)
log.Debugf("http api request done: resp=%+v, req=%+v, err=%v", resp, req, err)
//////////////////////////////////////////////////////////////////////////
// err resp:
if err != nil {
// type err:
if e, ok := err.(*errors.HttpError); ok {
ctx.JSON(int(e.GetCode()), ResponseData{
Code: int64(e.GetCode()),
Message: e.GetDetail(),
Data: nil,
})
return
}
// type err:
if e, ok := err.(*microErr.Error); ok {
ctx.JSON(int(e.GetCode()), ResponseData{
Code: int64(e.GetCode()),
Message: e.GetDetail(),
Data: nil,
})
return
}
//biz err: 500
ctx.JSON(http.StatusInternalServerError, ResponseData{
Code: http.StatusInternalServerError,
Message: http.StatusText(http.StatusInternalServerError),
Data: nil,
})
return
}
//////////////////////////////////////////////////////////////////////////
// ok resp:
ctx.JSON(http.StatusOK, ResponseData{
Code: http.StatusOK,
Message: http.StatusText(http.StatusOK),
Data: resp,
})
return
}