Files
pig-farm-controller/internal/api/api.go

133 lines
3.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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/logs"
"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
// logger 日志记录器
logger *logs.Logger
}
// NewAPI 创建并返回一个新的API实例
// 初始化Gin引擎和相关配置
func NewAPI(cfg *config.Config) *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())
return &API{
engine: engine,
config: cfg,
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("Starting HTTP server on %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 server startup failed: %v", err))
}
}()
return nil
}
// Stop 停止HTTP服务器
func (a *API) Stop() error {
a.logger.Info("Stopping HTTP server")
// 创建一个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 server shutdown error: %v", err))
return err
}
a.logger.Info("HTTP server stopped")
return nil
}
// setupRoutes 配置路由
func (a *API) setupRoutes() {
// 基础路由示例
a.engine.GET("/health", a.healthHandler)
// 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": "Pig Farm Controller API is running",
})
}