hotgo/server/internal/cmd/http.go

103 lines
2.5 KiB
Go
Raw Normal View History

2022-11-24 23:37:34 +08:00
// Package cmd
2022-02-25 17:11:17 +08:00
// @Link https://github.com/bufanyun/hotgo
// @Copyright Copyright (c) 2022 HotGo CLI
2022-11-24 23:37:34 +08:00
// @Author Ms <133814250@qq.com>
2022-02-25 17:11:17 +08:00
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
2022-11-24 23:37:34 +08:00
package cmd
2022-02-25 17:11:17 +08:00
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
2022-11-24 23:37:34 +08:00
"hotgo/internal/library/casbin"
"hotgo/internal/model"
"hotgo/internal/router"
"hotgo/internal/service"
2022-02-25 17:11:17 +08:00
)
var (
2022-11-24 23:37:34 +08:00
Http = &gcmd.Command{
Name: "http",
Usage: "http",
Brief: "HTTP服务",
2022-02-25 17:11:17 +08:00
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
if _, err := g.Cfg().Get(ctx, "hotgo.debug"); err != nil {
g.Log().Fatal(ctx, "配置读取异常:", err, "\r\n你确定 config/config.yaml 文件存在且格式正确吗?\r\n")
}
2022-11-24 23:37:34 +08:00
// 加载权限
casbin.InitEnforcer(ctx)
2022-02-25 17:11:17 +08:00
s := g.Server()
// 错误状态码接管
s.BindStatusHandler(404, func(r *ghttp.Request) {
r.Response.Writeln("404 - 你似乎来到了没有知识存在的荒原…")
})
s.BindStatusHandler(403, func(r *ghttp.Request) {
r.Response.Writeln("403 - 网站拒绝显示此网页")
})
// 请求结束事件回调
2022-11-24 23:37:34 +08:00
s.BindHookHandler("/*any", ghttp.HookAfterOutput, service.Hook().GlobalLog)
2022-02-25 17:11:17 +08:00
s.Group("/", func(group *ghttp.RouterGroup) {
// 注册全局中间件
group.Middleware(
2022-11-24 23:37:34 +08:00
service.Middleware().Ctx, //必须第一个加载
service.Middleware().CORS,
service.Middleware().DemoLimit,
service.Middleware().ResponseHandler,
2022-02-25 17:11:17 +08:00
)
// 注册默认首页路由
group.ALL("/", func(r *ghttp.Request) {
r.Response.Write("hello hotGo!!")
2022-11-24 23:37:34 +08:00
return
})
group.ALL("/login", func(r *ghttp.Request) {
r.Response.RedirectTo("/admin")
2022-02-25 17:11:17 +08:00
})
// 注册后台路由
router.Admin(ctx, group)
2022-11-24 23:37:34 +08:00
// 注册前台路由
2022-02-25 17:11:17 +08:00
router.Api(ctx, group)
2022-11-24 23:37:34 +08:00
// 注册websocket路由
router.WebSocket(ctx, group)
2022-02-25 17:11:17 +08:00
})
2022-11-24 23:37:34 +08:00
// 启动定时任务
service.SysCron().StartCron(ctx)
2022-02-25 17:11:17 +08:00
2022-11-24 23:37:34 +08:00
// 信号监听
signalListen(ctx, signalHandlerForCron, signalHandlerForWebSocket)
// 开启https访问
var (
sSLConfig *model.SSLConfig
ssl, _ = g.Cfg().Get(ctx, "hotgo.ssl")
)
if err := ssl.Struct(&sSLConfig); err != nil {
g.Log().Fatalf(ctx, "hotgo启动失败, ssl err:", err)
return err
}
if sSLConfig != nil && sSLConfig.Switch {
s.EnableHTTPS(sSLConfig.CrtPath, sSLConfig.KeyPath)
}
2022-02-25 17:11:17 +08:00
// Just run the server.
s.Run()
2022-11-24 23:37:34 +08:00
2022-02-25 17:11:17 +08:00
return nil
},
}
)