beego.go
2.8 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
81
82
83
84
85
86
87
88
89
package beego
import (
"fmt"
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/beego/beego/v2/server/web/context"
"github.com/linmadan/egglib-go/web/beego/filters"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
"net/http"
"os"
"strconv"
"strings"
. "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/log"
_ "gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/port/beego/routers"
)
func init() {
web.BConfig.AppName = "character-library-metadata-bastion"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev" //"prod"
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego/routers"
if os.Getenv("RUN_MODE") != "" {
web.BConfig.RunMode = os.Getenv("RUN_MODE")
}
if os.Getenv("HTTP_PORT") != "" {
portStr := os.Getenv("HTTP_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPPort = port
}
}
//https支持
web.BConfig.Listen.EnableHTTPS = true
web.BConfig.Listen.HTTPSPort = 443
web.BConfig.Listen.HTTPSCertFile = "./config/fjmaimaimai.com_bundle.crt"
web.BConfig.Listen.HTTPSKeyFile = "./config/fjmaimaimai.com.key"
//进程内监控
//web.BConfig.Listen.EnableAdmin = true
//web.BConfig.Listen.AdminPort = 8088
if os.Getenv("HTTPS_PORT") != "" {
portStr := os.Getenv("HTTPS_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPSPort = port
}
}
web.InsertFilter("/*", web.BeforeRouter, filters.AllowCors())
web.InsertFilter("/*", web.BeforeRouter, JwtFilter())
web.InsertFilter("/*", web.BeforeExec, CreateRequestLogFilter(true)) // filters.CreateRequstLogFilter(Logger)
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
func CreateRequestLogFilter(console bool) func(ctx *context.Context) {
return func(ctx *context.Context) {
msg := fmt.Sprintf("beego | %v | %v \n %v", ctx.Input.Method(), ctx.Input.URL(), string(ctx.Input.RequestBody))
logs.Debug(msg)
if console {
fmt.Println(msg)
}
}
}
func JwtFilter() func(ctx *context.Context) {
return func(ctx *context.Context) {
//token := ctx.Request.Header.Get("Authorization")
token := ctx.Request.Header.Get("x-mmm-accesstoken")
if len(token) > 0 {
token = strings.TrimPrefix(token, "Bearer ")
userToken := &domain.UserToken{}
err := userToken.ParseToken(token)
if err != nil {
ctx.Output.SetStatus(http.StatusOK)
ctx.Output.JSON(map[string]interface{}{
"msg": "token 过期或无效,需刷新令牌",
"code": 901,
"data": struct{}{},
}, false, false)
return
}
ctx.Input.SetData("UserToken", userToken)
}
}
}