package router import ( "ArmedPolice/app/api" "ArmedPolice/config" "ArmedPolice/router/rate" "io" "net/http" "os" "time" "github.com/gin-gonic/gin" ) type Router struct { *Option handler *gin.Engine } type ( Option struct { Mode string IsCors bool *RateLimitConfig } // RateLimitConfig 限流配置 RateLimitConfig struct { IsRate bool `json:"is_rate"` Limit int `json:"limit"` Capacity int `json:"capacity"` } ) func (this *Router) registerAPI() { apiPrefix := "/api" g := this.handler.Group(apiPrefix) g.Use() // 登录验证 g.Use(NeedLogin(AddSkipperURL([]string{ apiPrefix + "/v1/account/login", apiPrefix + "/v1/account/logout", apiPrefix + "/v1/user/info", }...))) v1 := g.Group("/v1") // Account 接口管理 accountV1 := v1.Group("/account") { _api := new(api.Account) accountV1.POST("/login", _api.Login) accountV1.POST("/logout", _api.Logout) } // User 用户管理 UserV1 := v1.Group("/user") { _api := new(api.User) UserV1.GET("/info", _api.Info) UserV1.GET("/list", _api.List) } } func (this *Router) Init() *gin.Engine { gin.SetMode(this.Mode) app := gin.New() if this.IsCors { app.Use(Cors()) } app.NoRoute(NoRouteHandler()) app.NoMethod(NoMethodHandler()) app.Use(LoggerHandle("log/gin.log", 3)) app.Use(TimeoutHandle(time.Second * 30)) app.Use(RecoveryHandler()) if this.RateLimitConfig != nil { if this.RateLimitConfig.IsRate { rate.NewIPRateLimiter()(this.RateLimitConfig.Limit, this.RateLimitConfig.Capacity) app.Use(rate.RequestIPRateLimiter()(this.RateLimitConfig.Limit, this.RateLimitConfig.Capacity)) } } if config.IsDebug() { gin.DefaultWriter = io.MultiWriter(os.Stdout) app.StaticFS("/api-docs", http.Dir("./doc")) } app.StaticFS("/upload", http.Dir("./upload")) app.MaxMultipartMemory = 4 << 20 this.handler = app // 注册路由 this.registerAPI() return app } func NewRouter(option *Option) *Router { return &Router{Option: option} }