feat: refactor application to use Gin framework, update routing and middleware handling
This commit is contained in:
@@ -32,14 +32,14 @@ func NewApp(configPath string) (*App, error) {
|
||||
return nil, fmt.Errorf("初始化服务失败: %w", err)
|
||||
}
|
||||
|
||||
// 设置路由
|
||||
handler, err := routes.SetupRoutes(cfg, ttsService)
|
||||
// 设置Gin路由
|
||||
router, err := routes.SetupRoutes(cfg, ttsService)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("设置路由失败: %w", err)
|
||||
}
|
||||
|
||||
// 创建HTTP服务器
|
||||
server := New(cfg, handler)
|
||||
server := New(cfg, router)
|
||||
|
||||
return &App{
|
||||
server: server,
|
||||
|
||||
@@ -3,43 +3,36 @@ package server
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"tts/internal/config"
|
||||
)
|
||||
|
||||
// Server 封装HTTP服务器
|
||||
type Server struct {
|
||||
server *http.Server
|
||||
router *gin.Engine
|
||||
basePath string
|
||||
port int
|
||||
}
|
||||
|
||||
// New 创建新的HTTP服务器
|
||||
func New(cfg *config.Config, handler http.Handler) *Server {
|
||||
// 创建HTTP服务器
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
|
||||
Handler: handler,
|
||||
ReadTimeout: time.Duration(cfg.Server.ReadTimeout) * time.Second,
|
||||
WriteTimeout: time.Duration(cfg.Server.WriteTimeout) * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
func New(cfg *config.Config, router *gin.Engine) *Server {
|
||||
return &Server{
|
||||
server: httpServer,
|
||||
router: router,
|
||||
basePath: cfg.Server.BasePath,
|
||||
port: cfg.Server.Port,
|
||||
}
|
||||
}
|
||||
|
||||
// Start 启动HTTP服务器
|
||||
func (s *Server) Start() error {
|
||||
fmt.Printf("服务启动在 %s\n", s.server.Addr)
|
||||
return s.server.ListenAndServe()
|
||||
addr := fmt.Sprintf(":%d", s.port)
|
||||
return s.router.Run(addr)
|
||||
}
|
||||
|
||||
// Shutdown 优雅关闭服务器
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
fmt.Println("正在关闭HTTP服务器...")
|
||||
return s.server.Shutdown(ctx)
|
||||
// Gin 本身没有提供 Shutdown 方法,需要手动实现
|
||||
// 这里可以添加自定义的关闭逻辑
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user