base.go
1.9 KB
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
package controllers
import (
"bytes"
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/tiptok/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/protocol"
"strings"
)
type BaseController struct {
beego.Controller
}
func (controller BaseController) JsonUnmarshal(v interface{}) error {
body := controller.Ctx.Input.RequestBody
if len(body) == 0 {
body = []byte("{}")
}
newDecoder := json.NewDecoder(bytes.NewReader(body))
newDecoder.UseNumber()
err := newDecoder.Decode(v)
return err
}
func (controller BaseController) BodyKeys(firstCaseToUpper bool) []string {
var bodyKV map[string]json.RawMessage
controller.JsonUnmarshal(&bodyKV)
if len(bodyKV) == 0 {
return []string{}
}
var list []string
for k, _ := range bodyKV {
list = append(list, common.CamelCase(k, true))
}
return list
}
func (controller *BaseController) Resp(msg *protocol.ResponseMessage) {
if msg.Errno > 0 {
msg.Errno = -1
}
controller.Data["json"] = msg
controller.Ctx.Input.SetData("outputData", msg)
controller.ServeJSON()
}
func (controller BaseController) GetLimitInfo() (offset int, limit int) {
offset, _ = controller.GetInt("pageNumber")
limit, _ = controller.GetInt("pageSize")
if offset > 0 {
offset = (offset - 1) * limit
}
return
}
//获取请求头信息
func (controller *BaseController) GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
if v := ctx.Input.GetData("x-mmm-id"); v != nil {
h.UserId = int64(v.(int))
}
if v := ctx.Input.GetData("x-mmm-uname"); v != nil {
h.UserName = v.(string)
}
h.Token = ctx.Input.Header("Authorization")
if len(h.Token) > 0 && len(strings.Split(h.Token, " ")) > 1 {
h.Token = strings.Split(h.Token, " ")[1]
}
h.BodyKeys = controller.BodyKeys(true)
if v := ctx.Request.URL.Query(); len(v) > 0 {
for k, _ := range v {
h.BodyKeys = append(h.BodyKeys, common.CamelCase(k, true))
}
}
return h
}