feat:完善项目
This commit is contained in:
67
router/router.go
Normal file
67
router/router.go
Normal file
@ -0,0 +1,67 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"SciencesServer/config"
|
||||
"SciencesServer/router/rate"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Router struct {
|
||||
*Option
|
||||
}
|
||||
|
||||
type (
|
||||
Option struct {
|
||||
Mode string
|
||||
IsCors bool
|
||||
*RateLimitConfig
|
||||
}
|
||||
// RouterLimitConfig 限流配置
|
||||
RateLimitConfig struct {
|
||||
IsRate bool `json:"is_rate"`
|
||||
Limit int `json:"limit"`
|
||||
Capacity int `json:"capacity"`
|
||||
}
|
||||
)
|
||||
|
||||
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"))
|
||||
// 注册路由
|
||||
register(app)
|
||||
|
||||
app.MaxMultipartMemory = 4 << 20
|
||||
|
||||
return app
|
||||
}
|
||||
|
||||
func NewRouter(option *Option) *Router {
|
||||
return &Router{option}
|
||||
}
|
Reference in New Issue
Block a user