-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_api.go
63 lines (54 loc) · 1.58 KB
/
base_api.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
package apicontrollers
import (
"library/common"
"runtime"
"github.com/astaxie/beego"
"github.com/dgrijalva/jwt-go"
)
//TODO 另一版的api验证 废弃
//基类
type BaseApiController struct {
beego.Controller
}
var AppId int
// Prepare implemented Prepare method for baseRouter.
func (c *BaseApiController) Prepare() {
//获取panic
defer func() {
if panic_err := recover(); panic_err != nil {
var buf []byte = make([]byte, 1024)
runtimec := runtime.Stack(buf, false)
beego.Error("控制器错误:", panic_err, string(buf[0:runtimec]))
//c.Data["json"] = map[string]string{
// "Error": string(buf[0:runtimec]),
// "Result": common.GetString(panic_err),
//}
//c.ServeJSON()
//c.StopRun()
}
}()
//正式环境则需要验证Token并且需要使用HTTPS访问
//if beego.BConfig.RunMode == "prod" {
if c.Ctx.Input.IsSecure() == false {
//c.Data["json"] = map[string]string{"errcode": "101", "errmsg": "请使用HTTPS请求API:" + c.Ctx.Input.Site() + ":" + beego.AppConfig.String("HttpsPort")}
//c.ServeJSON()
//c.StopRun()
}
//验证token
tokenString := c.Ctx.Input.Header("Authorization")
if tokenString == "" {
c.Data["json"] = map[string]string{"errcode": "102", "errmsg": "token错误"}
c.ServeJSON()
c.StopRun()
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return []byte(beego.AppConfig.String("SecretKey")), nil
})
AppId = common.GetInt(token.Claims["iss"])
if err != nil {
c.Data["json"] = map[string]string{"errcode": "103", "errmsg": "token验证失败"}
c.ServeJSON()
c.StopRun()
}
//}
}