-
Notifications
You must be signed in to change notification settings - Fork 0
/
route_management.go
116 lines (99 loc) · 2.48 KB
/
route_management.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
package plugin
import (
"github.com/gin-gonic/gin"
"io"
"log"
"net/http"
"brief_framework/logger"
"encoding/json"
)
type GetHandler func(map[string]string) interface{}
type PostHandler func([]byte) interface{}
type PostHandlerMap func(map[string]string) interface{}
type OptionHandler func(map[string]string) interface{}
type PathHandler struct {
Path string
Handler interface{}
}
var ResSlice []*PathHandler
//Add handler to map
func RegisterHandler(relativePath string, p interface{}) {
ResSlice = append(ResSlice, &PathHandler{relativePath, p})
}
func getQueryMap(c *gin.Context) map[string]string {
m := make(map[string]string)
for k, v := range c.Request.URL.Query() {
m[k] = v[0]
}
return m
}
func getPostByteSlice(c *gin.Context) []byte {
buf := make([]byte, 4096)
n, err := c.Request.Body.Read(buf)
if err == io.EOF {
//read all
} else {
log.Printf("Read Error: %s\n", err)
}
c.Set("postByte", string(buf[0:n]))
return buf[0:n]
}
func getPostMap(c *gin.Context) map[string]string {
m := make(map[string]string)
for k, v := range c.Request.PostForm {
m[k] = v[0]
}
return m
}
func DoGetProcess(c *gin.Context, p GetHandler) {
obj := p(getQueryMap(c))
doFinalProcess(c, obj)
}
func DoPostProcess(c *gin.Context, p PostHandler) {
obj := p(getPostByteSlice(c))
doFinalProcess(c, obj)
}
func DoOptionProcess(c *gin.Context, p OptionHandler) {
obj := p(nil)
doFinalProcess(c, obj)
}
func DoPostProcessMap(c *gin.Context, p PostHandlerMap) {
obj := p(getPostMap(c))
doFinalProcess(c, obj)
}
func doFinalProcess(c *gin.Context, obj interface{}) {
r, err := json.Marshal(obj)
var s string
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
} else {
c.String(http.StatusOK, string(r))
}
c.Set("returnString", string(s)) //for logging
}
func DefaultHandle(map[string]string) interface{} {
return "OK"
}
func InitHandler(router *gin.Engine) {
for _, v := range ResSlice {
if p, ok := v.Handler.(GetHandler); ok {
router.GET(v.Path, func(c *gin.Context) {
DoGetProcess(c, p)
})
} else if p, ok := v.Handler.(PostHandler); ok {
router.POST(v.Path, func(c *gin.Context) {
DoPostProcess(c, p)
})
} else if p, ok := v.Handler.(PostHandlerMap); ok {
router.POST(v.Path, func(c *gin.Context) {
DoPostProcessMap(c, p)
})
} else if p, ok := v.Handler.(OptionHandler); ok {
router.OPTIONS(v.Path, func(c *gin.Context) {
DoOptionProcess(c, p)
})
} else {
logger.Instance().Warn("Handler can not recognize")
}
}
}