实现基础web服务器
This commit is contained in:
@@ -2,3 +2,124 @@
|
||||
// 负责处理所有外部请求,包括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 健康检查处理函数
|
||||
func (a *API) healthHandler(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"status": "ok",
|
||||
"message": "Pig Farm Controller API is running",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -26,6 +26,15 @@ type ServerConfig struct {
|
||||
|
||||
// Port 服务器监听端口
|
||||
Port int `yaml:"port"`
|
||||
|
||||
// ReadTimeout 读取超时(秒)
|
||||
ReadTimeout int `yaml:"read_timeout"`
|
||||
|
||||
// WriteTimeout 写入超时(秒)
|
||||
WriteTimeout int `yaml:"write_timeout"`
|
||||
|
||||
// IdleTimeout 空闲超时(秒)
|
||||
IdleTimeout int `yaml:"idle_timeout"`
|
||||
}
|
||||
|
||||
// DatabaseConfig 代表数据库配置
|
||||
|
||||
@@ -5,10 +5,12 @@ package core
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/api"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/config"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/logs"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/storage/db"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/task"
|
||||
)
|
||||
|
||||
// Application 代表核心应用结构
|
||||
@@ -17,6 +19,12 @@ type Application struct {
|
||||
// Storage 存储组件实例
|
||||
Storage db.Storage
|
||||
|
||||
// API API组件实例
|
||||
API *api.API
|
||||
|
||||
// TaskExecutor 任务执行器组件实例
|
||||
TaskExecutor *task.Executor
|
||||
|
||||
// Config 应用配置
|
||||
Config *config.Config
|
||||
}
|
||||
@@ -35,9 +43,19 @@ func NewApplication(cfg *config.Config) *Application {
|
||||
// 初始化存储组件
|
||||
store := db.NewStorage(connectionString, maxOpenConns, maxIdleConns, connMaxLifetime)
|
||||
|
||||
// 初始化API组件
|
||||
apiInstance := api.NewAPI(cfg)
|
||||
|
||||
// 初始化任务执行器组件(使用5个工作协程)
|
||||
taskExecutor := task.NewExecutor(5)
|
||||
|
||||
return &Application{
|
||||
Storage: store,
|
||||
Config: cfg,
|
||||
Storage: store,
|
||||
Storage: store,
|
||||
API: apiInstance,
|
||||
TaskExecutor: taskExecutor,
|
||||
Config: cfg,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,21 +66,38 @@ func (app *Application) Start() error {
|
||||
if err := app.Storage.Connect(); err != nil {
|
||||
return fmt.Errorf("failed to connect to storage: %v", err)
|
||||
}
|
||||
log.Println("Storage connected successfully")
|
||||
app.logger.Info("Storage connected successfully")
|
||||
|
||||
// 启动API组件
|
||||
if err := app.API.Start(); err != nil {
|
||||
return fmt.Errorf("failed to start API: %v", err)
|
||||
}
|
||||
app.logger.Info("API started successfully")
|
||||
|
||||
// 启动任务执行器组件
|
||||
app.TaskExecutor.Start()
|
||||
app.logger.Info("Task executor started successfully")
|
||||
|
||||
// TODO: 启动其他核心组件
|
||||
return nil
|
||||
}
|
||||
|
||||
// Stop 停止核心应用
|
||||
// 按正确顺序停止所有核心组件
|
||||
func (app *Application) Stop() error {
|
||||
// 停止API组件
|
||||
if err := app.API.Stop(); err != nil {
|
||||
app.logger.Error(fmt.Sprintf("Failed to stop API: %v", err))
|
||||
}
|
||||
|
||||
// 停止任务执行器组件
|
||||
app.TaskExecutor.Stop()
|
||||
app.logger.Info("Task executor stopped successfully")
|
||||
|
||||
// 停止存储组件
|
||||
if err := app.Storage.Disconnect(); err != nil {
|
||||
return fmt.Errorf("failed to disconnect from storage: %v", err)
|
||||
}
|
||||
log.Println("Storage disconnected successfully")
|
||||
app.logger.Info("Storage disconnected successfully")
|
||||
|
||||
// TODO: 停止其他核心组件
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package logs
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Logger 代表日志记录器结构
|
||||
@@ -16,26 +17,26 @@ type Logger struct {
|
||||
// NewLogger 创建并返回一个新的日志记录器实例
|
||||
func NewLogger() *Logger {
|
||||
return &Logger{
|
||||
logger: log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile),
|
||||
logger: log.New(os.Stdout, "", 0),
|
||||
}
|
||||
}
|
||||
|
||||
// Info 记录信息级别日志
|
||||
func (l *Logger) Info(message string) {
|
||||
l.logger.Printf("[INFO] %s", message)
|
||||
l.logger.Printf("[INFO] %s %s", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||
|
||||
// Error 记录错误级别日志
|
||||
func (l *Logger) Error(message string) {
|
||||
l.logger.Printf("[ERROR] %s", message)
|
||||
l.logger.Printf("[ERROR] %s %s", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||
|
||||
// Debug 记录调试级别日志
|
||||
func (l *Logger) Debug(message string) {
|
||||
l.logger.Printf("[DEBUG] %s", message)
|
||||
l.logger.Printf("[DEBUG] %s %s", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||
|
||||
// Warn 记录警告级别日志
|
||||
func (l *Logger) Warn(message string) {
|
||||
l.logger.Printf("[WARN] %s", message)
|
||||
l.logger.Printf("[WARN] %s %s", time.Now().Format(time.RFC3339), message)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user