Files
bl/login/internal/cmd/cmd.go
昔念 6f51a2e349
All checks were successful
ci/woodpecker/push/my-first-workflow Pipeline was successful
1
2026-04-15 00:07:36 +08:00

98 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package cmd
import (
"blazing/common/rpc"
"blazing/cool"
"context"
"time"
"github.com/yudeguang/ratelimit"
i18n "blazing/modules/base/middleware"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
"github.com/xiaoqidun/qqwry"
)
var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "start http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
r := parser.GetOpt("debug", false)
if r.Bool() {
g.DB().SetDebug(true)
// service.NewServerService().SetServerScreen(0, "sss")
cool.Config.ServerInfo.IsDebug = 1
}
if err = cool.RunAutoMigrate(); err != nil {
return err
}
if cool.IsRedisMode {
go rpc.ListenFunc(ctx)
}
// // 从文件加载IP数据库
if err := qqwry.LoadFile("public/qqwry.ipdb"); err != nil {
panic(err)
}
//go robot()
//go reg()
go startrobot()
s := g.Server()
s.Use(Limiter, ghttp.MiddlewareHandlerResponse)
s.EnableAdmin()
s.SetServerAgent(cool.Config.Name)
s.BindHookHandler("/*", ghttp.HookBeforeServe, beforeServeHook)
// runtime.SetMutexProfileFraction(1) // (非必需)开启对锁调用的跟踪
// runtime.SetBlockProfileRate(1) // (非必需)开启对阻塞操作的跟踪
// s.EnablePProf()
// 如果存在 data/cool-admin-vue/dist 目录,则设置为主目录
if gfile.IsDir("public") {
s.SetServerRoot("public")
}
// i18n 信息
s.BindHandler("/i18n", i18n.I18nInfo)
// g.Server().BindMiddleware("/*", MiddlewareCORS)
s.Run()
return nil
},
}
)
func beforeServeHook(r *ghttp.Request) {
//glog.Debugf(r.GetCtx(), "beforeServeHook [is file:%v] URI:%s", r.IsFileRequest(), r.RequestURI)
r.Response.CORSDefault()
}
// var limiter = rate.NewLimiter(rate.Limit(150), 50)
var limiter *ratelimit.Rule = ratelimit.NewRule()
// 简单规则案例
func init() {
//步骤二:增加一条或者多条规则组成复合规则,此复合规则必须至少包含一条规则
limiter.AddRule(time.Second*1, 20)
//步骤三:调用函数判断某用户是否允许访问 allow:= r.AllowVisit(user)
}
// Limiter is a middleware that implements rate limiting for all HTTP requests.
// It returns HTTP 429 (Too Many Requests) when the rate limit is exceeded.
func Limiter(r *ghttp.Request) {
// 3. 为任意键 "some-key" 获取一个速率限制器
// - rate.Limit(2): 表示速率为 "每秒2个请求"
// - 2: 表示桶的容量 (Burst)允许瞬时处理2个请求
ip := r.GetClientIp()
if !limiter.AllowVisitByIP4(ip) {
r.Response.WriteStatusExit(429) // Return 429 Too Many Requests
r.ExitAll()
}
r.Middleware.Next()
}