-
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathapi-base.go
61 lines (49 loc) · 1.14 KB
/
api-base.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
package controllers
import "github.com/beego/beego/v2/core/logs"
type APIBaseController struct {
BaseController
}
// JSONResponse http://stackoverflow.com/a/12979961
type JSONResponse struct {
Status string `json:"status"`
Message string `json:"message"`
Code string `json:"code,omitempty"`
Data interface{} `json:"data,omitempty"`
}
func NewJSONResponse() *JSONResponse {
response := &JSONResponse{
Status: "success",
}
return response
}
func (c *APIBaseController) Prepare() {
c.EnableXSRF = false
c.BaseController.Prepare()
}
func (c *APIBaseController) NestPrepare() {
if !c.IsLogin {
c.ServeJSONError("You are not authorized")
return
}
}
func (c *APIBaseController) ServeJSONMessage(message string) {
r := NewJSONResponse()
r.Message = message
c.Data["json"] = r
c.ServeJSON()
}
func (c *APIBaseController) ServeJSONData(data interface{}) {
r := NewJSONResponse()
r.Data = data
c.Data["json"] = r
c.ServeJSON()
}
func (c *APIBaseController) ServeJSONError(message string) {
c.Data["json"] = JSONResponse{
Status: "error",
Message: message,
}
logs.Warning(message)
c.Ctx.Output.SetStatus(400)
c.ServeJSON()
}