Files
xiaohongshu-mcp/app_server.go
zy a7e975cf7c refactor: 重构代码架构,解耦处理器和服务 (#13)
重大架构改进:
- 移除全局变量 xiaohongshuService,改用依赖注入
- 将代码按职责分离到不同文件:
  * app_server.go - 核心服务器结构
  * types.go - 统一类型定义
  * routes.go - 路由配置
  * middleware.go - 中间件
  * handlers_api.go - REST API 处理器
  * handlers_mcp.go - MCP 协议处理器
- 将通用工具函数从 AppServer 方法改为独立函数
- 删除未使用的类型定义(LoginWaitRequest)
- 修复 JSON 编码错误处理

优势:
 更好的依赖注入模式
 清晰的职责分离
 提高代码可测试性
 符合 Go 最佳实践
 降低耦合度,提高内聚性

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-08-17 16:15:54 +08:00

67 lines
1.4 KiB
Go

package main
import (
"context"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// AppServer 应用服务器结构体,封装所有服务和处理器
type AppServer struct {
xiaohongshuService *XiaohongshuService
router *gin.Engine
httpServer *http.Server
}
// NewAppServer 创建新的应用服务器实例
func NewAppServer(xiaohongshuService *XiaohongshuService) *AppServer {
return &AppServer{
xiaohongshuService: xiaohongshuService,
}
}
// Start 启动服务器
func (s *AppServer) Start(port string) error {
s.router = setupRoutes(s)
s.httpServer = &http.Server{
Addr: port,
Handler: s.router,
}
// 启动服务器的 goroutine
go func() {
logrus.Infof("启动 HTTP 服务器: %s", port)
if err := s.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logrus.Errorf("服务器启动失败: %v", err)
os.Exit(1)
}
}()
// 等待中断信号
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logrus.Infof("正在关闭服务器...")
// 优雅关闭
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// 关闭 HTTP 服务器
if err := s.httpServer.Shutdown(ctx); err != nil {
logrus.Errorf("服务器关闭失败: %v", err)
return err
}
logrus.Infof("服务器已关闭")
return nil
}