重大架构改进: - 移除全局变量 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>
94 lines
2.3 KiB
Go
94 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// respondError 返回错误响应
|
|
func respondError(c *gin.Context, statusCode int, code, message string, details any) {
|
|
response := ErrorResponse{
|
|
Error: message,
|
|
Code: code,
|
|
Details: details,
|
|
}
|
|
|
|
logrus.Errorf("%s %s %s %d", c.Request.Method, c.Request.URL.Path,
|
|
c.GetString("account"), statusCode)
|
|
|
|
c.JSON(statusCode, response)
|
|
}
|
|
|
|
// respondSuccess 返回成功响应
|
|
func respondSuccess(c *gin.Context, data any, message string) {
|
|
response := SuccessResponse{
|
|
Success: true,
|
|
Data: data,
|
|
Message: message,
|
|
}
|
|
|
|
logrus.Infof("%s %s %s %d", c.Request.Method, c.Request.URL.Path,
|
|
c.GetString("account"), http.StatusOK)
|
|
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// checkLoginStatusHandler 检查登录状态
|
|
func (s *AppServer) checkLoginStatusHandler(c *gin.Context) {
|
|
status, err := s.xiaohongshuService.CheckLoginStatus(c.Request.Context())
|
|
if err != nil {
|
|
respondError(c, http.StatusInternalServerError, "STATUS_CHECK_FAILED",
|
|
"检查登录状态失败", err.Error())
|
|
return
|
|
}
|
|
|
|
c.Set("account", "ai-report")
|
|
respondSuccess(c, status, "检查登录状态成功")
|
|
}
|
|
|
|
// publishHandler 发布内容
|
|
func (s *AppServer) publishHandler(c *gin.Context) {
|
|
var req PublishRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
respondError(c, http.StatusBadRequest, "INVALID_REQUEST",
|
|
"请求参数错误", err.Error())
|
|
return
|
|
}
|
|
|
|
// 执行发布
|
|
result, err := s.xiaohongshuService.PublishContent(c.Request.Context(), &req)
|
|
if err != nil {
|
|
respondError(c, http.StatusInternalServerError, "PUBLISH_FAILED",
|
|
"发布失败", err.Error())
|
|
return
|
|
}
|
|
|
|
respondSuccess(c, result, "发布成功")
|
|
}
|
|
|
|
// listFeedsHandler 获取Feeds列表
|
|
func (s *AppServer) listFeedsHandler(c *gin.Context) {
|
|
// 获取 Feeds 列表
|
|
result, err := s.xiaohongshuService.ListFeeds(c.Request.Context())
|
|
if err != nil {
|
|
respondError(c, http.StatusInternalServerError, "LIST_FEEDS_FAILED",
|
|
"获取Feeds列表失败", err.Error())
|
|
return
|
|
}
|
|
|
|
c.Set("account", "ai-report")
|
|
respondSuccess(c, result, "获取Feeds列表成功")
|
|
}
|
|
|
|
// healthHandler 健康检查
|
|
func healthHandler(c *gin.Context) {
|
|
respondSuccess(c, map[string]any{
|
|
"status": "healthy",
|
|
"service": "xiaohongshu-mcp",
|
|
"account": "ai-report",
|
|
"timestamp": "now",
|
|
}, "服务正常")
|
|
}
|