-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller.go
108 lines (94 loc) · 2.64 KB
/
controller.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 api
import (
"fastgo/module/util"
"fmt"
"reflect"
"github.com/gosexy/to"
"github.com/valyala/fasthttp"
)
type Controller struct {
UserId string
}
type RetData struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type InputData map[int]string
type DataNil struct {
}
func (c *Controller) GetData(inputData interface{}, ctx *fasthttp.RequestCtx) {
if ctx.IsPost() {
c.collectPostData(inputData, ctx)
} else if ctx.IsGet() {
c.collectGetData(inputData, ctx)
}
}
func (c *Controller) collectGetData(inputData interface{}, ctx *fasthttp.RequestCtx) {
// log.Info("request data: " + string(ctx.QueryArgs().String()) + ", api: " + string(ctx.Path()))
s := reflect.ValueOf(inputData).Elem()
typeOf := s.Type()
for i := 0; i < s.NumField(); i++ {
field := typeOf.Field(i)
data := string(ctx.FormValue(field.Tag.Get("json")))
switch fmt.Sprintf("%s", field.Type) {
case "string":
s.Field(i).SetString(to.String(reflect.ValueOf(data)))
case "int":
fallthrough
case "int8":
fallthrough
case "int16":
fallthrough
case "int32":
fallthrough
case "int64":
s.Field(i).SetInt(to.Int64(reflect.ValueOf(data)))
case "uint":
fallthrough
case "uint8":
fallthrough
case "uint16":
fallthrough
case "uint32":
fallthrough
case "uint64":
s.Field(i).SetUint(to.Uint64(reflect.ValueOf(data)))
case "[]string":
tmpSlice := make([]string, 0)
util.JsonDecode(data, &tmpSlice)
s.Field(i).Set(reflect.ValueOf(tmpSlice))
case "[]uint8":
tmpSlice := make([]uint8, 0)
util.JsonDecode(data, &tmpSlice)
s.Field(i).Set(reflect.ValueOf(tmpSlice))
case "[]int":
tmpSlice := make([]int, 0)
util.JsonDecode(data, &tmpSlice)
s.Field(i).Set(reflect.ValueOf(tmpSlice))
case "[]int32":
tmpSlice := make([]int32, 0)
util.JsonDecode(data, &tmpSlice)
s.Field(i).Set(reflect.ValueOf(tmpSlice))
case "[]int64":
tmpSlice := make([]int64, 0)
util.JsonDecode(data, &tmpSlice)
s.Field(i).Set(reflect.ValueOf(tmpSlice))
}
}
}
func (c *Controller) collectPostData(inputData interface{}, ctx *fasthttp.RequestCtx) {
formData := string(ctx.PostBody())
// log.Infof("request data: %s, api: %v", formData, string(ctx.Path()))
util.JsonDecode(formData, &inputData)
return
}
func (c *Controller) SendText(ctx *fasthttp.RequestCtx, retData string) {
fmt.Fprintf(ctx, "%s", retData)
}
func (c *Controller) SendJson(ctx *fasthttp.RequestCtx, retData RetData) {
ctx.SetContentType("application/json")
retJson, _ := util.JsonEncode(retData)
// log.Info("response data: " + retJson + ", api: " + string(ctx.Path()))
fmt.Fprintf(ctx, "%s", retJson)
}