2025-12-19 00:01:43 +08:00
|
|
|
|
package server
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"net/http"
|
|
|
|
|
|
"time"
|
|
|
|
|
|
|
2025-12-26 10:42:08 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/config"
|
|
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/handler"
|
|
|
|
|
|
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
2025-12-26 00:17:55 -08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/service"
|
2025-12-26 10:42:08 +08:00
|
|
|
|
|
2025-12-19 00:01:43 +08:00
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
|
"github.com/google/wire"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// ProviderSet 提供服务器层的依赖
|
|
|
|
|
|
var ProviderSet = wire.NewSet(
|
|
|
|
|
|
ProvideRouter,
|
|
|
|
|
|
ProvideHTTPServer,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// ProvideRouter 提供路由器
|
2025-12-26 10:42:08 +08:00
|
|
|
|
func ProvideRouter(
|
|
|
|
|
|
cfg *config.Config,
|
|
|
|
|
|
handlers *handler.Handlers,
|
|
|
|
|
|
jwtAuth middleware2.JWTAuthMiddleware,
|
|
|
|
|
|
adminAuth middleware2.AdminAuthMiddleware,
|
|
|
|
|
|
apiKeyAuth middleware2.ApiKeyAuthMiddleware,
|
2025-12-26 00:17:55 -08:00
|
|
|
|
apiKeyService *service.ApiKeyService,
|
|
|
|
|
|
subscriptionService *service.SubscriptionService,
|
2025-12-26 10:42:08 +08:00
|
|
|
|
) *gin.Engine {
|
2025-12-19 00:01:43 +08:00
|
|
|
|
if cfg.Server.Mode == "release" {
|
|
|
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
r := gin.New()
|
2025-12-26 10:42:08 +08:00
|
|
|
|
r.Use(middleware2.Recovery())
|
2025-12-19 00:01:43 +08:00
|
|
|
|
|
2025-12-29 03:17:25 +08:00
|
|
|
|
return SetupRouter(r, handlers, jwtAuth, adminAuth, apiKeyAuth, apiKeyService, subscriptionService, cfg)
|
2025-12-19 00:01:43 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ProvideHTTPServer 提供 HTTP 服务器
|
|
|
|
|
|
func ProvideHTTPServer(cfg *config.Config, router *gin.Engine) *http.Server {
|
|
|
|
|
|
return &http.Server{
|
|
|
|
|
|
Addr: cfg.Server.Address(),
|
|
|
|
|
|
Handler: router,
|
|
|
|
|
|
// ReadHeaderTimeout: 读取请求头的超时时间,防止慢速请求头攻击
|
|
|
|
|
|
ReadHeaderTimeout: time.Duration(cfg.Server.ReadHeaderTimeout) * time.Second,
|
|
|
|
|
|
// IdleTimeout: 空闲连接超时时间,释放不活跃的连接资源
|
|
|
|
|
|
IdleTimeout: time.Duration(cfg.Server.IdleTimeout) * time.Second,
|
|
|
|
|
|
// 注意:不设置 WriteTimeout,因为流式响应可能持续十几分钟
|
|
|
|
|
|
// 不设置 ReadTimeout,因为大请求体可能需要较长时间读取
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|