149 lines
3.7 KiB
Go
149 lines
3.7 KiB
Go
// Package api 提供统一的API接口层
|
||
// 负责处理所有外部请求,包括HTTP和WebSocket接口
|
||
// 将请求路由到相应的服务层进行处理
|
||
package api
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"net/http"
|
||
"time"
|
||
|
||
"git.huangwc.com/pig/pig-farm-controller/internal/config"
|
||
"git.huangwc.com/pig/pig-farm-controller/internal/controller/user"
|
||
"git.huangwc.com/pig/pig-farm-controller/internal/logs"
|
||
"git.huangwc.com/pig/pig-farm-controller/internal/storage/repository"
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// API 代表API接口层的结构
|
||
// 包含Gin引擎和HTTP服务器实例
|
||
type API struct {
|
||
// engine Gin引擎实例
|
||
engine *gin.Engine
|
||
|
||
// server HTTP服务器实例
|
||
server *http.Server
|
||
|
||
// config 应用配置
|
||
config *config.Config
|
||
|
||
// userController 用户控制器
|
||
userController *user.Controller
|
||
|
||
// logger 日志记录器
|
||
logger *logs.Logger
|
||
}
|
||
|
||
// NewAPI 创建并返回一个新的API实例
|
||
// 初始化Gin引擎和相关配置
|
||
func NewAPI(cfg *config.Config, userRepo repository.UserRepo) *API {
|
||
// 设置Gin为发布模式
|
||
gin.SetMode(gin.ReleaseMode)
|
||
|
||
// 创建Gin引擎实例
|
||
engine := gin.New()
|
||
|
||
// 添加日志和恢复中间件
|
||
engine.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
|
||
return fmt.Sprintf("[API] %s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
|
||
param.ClientIP,
|
||
time.Now().Format(time.RFC3339),
|
||
param.Method,
|
||
param.Path,
|
||
param.Request.Proto,
|
||
param.StatusCode,
|
||
param.Latency,
|
||
param.Request.UserAgent(),
|
||
param.ErrorMessage,
|
||
)
|
||
}))
|
||
|
||
engine.Use(gin.Recovery())
|
||
|
||
// 创建用户控制器
|
||
userController := user.NewController(userRepo)
|
||
|
||
return &API{
|
||
engine: engine,
|
||
config: cfg,
|
||
userController: userController,
|
||
logger: logs.NewLogger(),
|
||
}
|
||
}
|
||
|
||
// Start 启动HTTP服务器
|
||
func (a *API) Start() error {
|
||
// 配置路由
|
||
a.setupRoutes()
|
||
|
||
// 创建HTTP服务器
|
||
a.server = &http.Server{
|
||
Addr: fmt.Sprintf("%s:%d", a.config.Server.Host, a.config.Server.Port),
|
||
Handler: a.engine,
|
||
// 添加服务器配置
|
||
ReadTimeout: time.Duration(a.config.Server.ReadTimeout) * time.Second,
|
||
WriteTimeout: time.Duration(a.config.Server.WriteTimeout) * time.Second,
|
||
IdleTimeout: time.Duration(a.config.Server.IdleTimeout) * time.Second,
|
||
}
|
||
|
||
// 启动HTTP服务器
|
||
a.logger.Info(fmt.Sprintf("正在启动HTTP服务器 %s:%d", a.config.Server.Host, a.config.Server.Port))
|
||
|
||
go func() {
|
||
if err := a.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||
a.logger.Error(fmt.Sprintf("HTTP服务器启动失败: %v", err))
|
||
}
|
||
}()
|
||
|
||
return nil
|
||
}
|
||
|
||
// Stop 停止HTTP服务器
|
||
func (a *API) Stop() error {
|
||
a.logger.Info("正在停止HTTP服务器")
|
||
|
||
// 创建一个5秒的超时上下文
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||
defer cancel()
|
||
|
||
// 优雅地关闭服务器
|
||
if err := a.server.Shutdown(ctx); err != nil {
|
||
a.logger.Error(fmt.Sprintf("HTTP服务器关闭错误: %v", err))
|
||
return err
|
||
}
|
||
|
||
a.logger.Info("HTTP服务器已停止")
|
||
return nil
|
||
}
|
||
|
||
// setupRoutes 配置路由
|
||
func (a *API) setupRoutes() {
|
||
// 基础路由示例
|
||
a.engine.GET("/health", a.healthHandler)
|
||
|
||
// 用户相关路由
|
||
userGroup := a.engine.Group("/api/v1/user")
|
||
{
|
||
userGroup.POST("/register", a.userController.Register)
|
||
userGroup.POST("/login", a.userController.Login)
|
||
}
|
||
|
||
// TODO: 添加更多路由
|
||
}
|
||
|
||
// healthHandler 健康检查处理函数
|
||
// @Summary 健康检查
|
||
// @Description 检查API服务是否正常运行
|
||
// @Tags health
|
||
// @Accept json
|
||
// @Produce json
|
||
// @Success 200 {object} map[string]interface{}
|
||
// @Router /health [get]
|
||
func (a *API) healthHandler(c *gin.Context) {
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"status": "ok",
|
||
"message": "猪场控制器API正在运行",
|
||
})
|
||
}
|