core.go
2.5 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
90
91
92
93
package main
import (
"flag"
"fmt"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/config"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/handler"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/api/internal/svc"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/db"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/cmd/ep/system/internal/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/gateway/smslib"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/tool"
"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
"net/http"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/rest"
)
var configFile = flag.String("f", "etc/core.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
// 系统设置
systemSetup(c)
// 服务初始化
opts := make([]rest.RunOption, 0)
opts = append(opts, rest.WithCustomCors(func(header http.Header) {
header.Set("Access-Control-Allow-Headers", "*")
}, func(writer http.ResponseWriter) {
}))
opts = append(opts, rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
if err != nil {
logx.Debugf("unauthorized: %s \n", err.Error())
}
httpx.WriteJson(w, http.StatusUnauthorized, xerr.Error(xerr.TokenExpireError, err.Error()))
return
}))
server := rest.MustNewServer(c.RestConf, opts...)
defer server.Stop()
ctx := svc.NewServiceContext(c)
handler.RegisterHandlers(server, ctx)
server.AddRoutes(RoutersOpenapi(ctx))
// 数据迁移
if c.Migrate {
db.Migrate(ctx.DB)
}
fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
server.Start()
}
func systemSetup(c config.Config) {
// 初始化Domain里面的配置
domain.ProjectName = c.Name
// 系统错误应答包装
httpx.SetErrorHandlerCtx(xerr.ErrorHandlerCtx)
// 系统成功应答包装
httpx.SetOkHandler(xerr.OkHandlerCtx)
}
func RoutersOpenapi(svc *svc.ServiceContext) []rest.Route {
return []rest.Route{
{
Method: http.MethodPost,
Path: "/v1/openapi/sms/send-sms-code",
Handler: smslib.SendSmsCodeHandler(svc.SmsService),
},
{
Method: http.MethodGet,
Path: "/log/:module",
Handler: tool.LogHandler(svc.Config.Log),
},
{
Method: http.MethodGet,
Path: "/cache/clear/:app",
Handler: tool.ClearCacheHandler(svc.Redis),
},
}
}