feat(backend): Go 服务骨架(配置、日志、数据库、中间件、Wire)
- config: Viper YAML 配置 + 环境变量覆盖 - logs: zap 结构化日志 + trace_id 链路追踪 + 敏感信息脱敏 - db: PostgreSQL (GORM) + Redis (go-redis) 连接管理 - middleware: Trace/Logger/CORS/Recovery 四层中间件 - provider: Wire 编译时依赖注入 - main.go: 优雅启动/关闭 HTTP 服务 Made-with: Cursor
This commit is contained in:
93
backend/go-service/pkg/db/postgres.go
Normal file
93
backend/go-service/pkg/db/postgres.go
Normal file
@@ -0,0 +1,93 @@
|
||||
// Package db 提供数据库连接管理
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/config"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"go.uber.org/zap"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// GormDB 全局 GORM 数据库实例
|
||||
var GormDB *gorm.DB
|
||||
|
||||
// zapGormLogger 将 GORM 日志适配到 zap
|
||||
type zapGormLogger struct{}
|
||||
|
||||
func (l *zapGormLogger) LogMode(logger.LogLevel) logger.Interface { return l }
|
||||
|
||||
func (l *zapGormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
|
||||
logs.Info(ctx, "gorm", fmt.Sprintf(msg, data...))
|
||||
}
|
||||
|
||||
func (l *zapGormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
|
||||
logs.Warn(ctx, "gorm", fmt.Sprintf(msg, data...))
|
||||
}
|
||||
|
||||
func (l *zapGormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
|
||||
logs.Error(ctx, "gorm", fmt.Sprintf(msg, data...))
|
||||
}
|
||||
|
||||
func (l *zapGormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
|
||||
elapsed := time.Since(begin)
|
||||
sql, rows := fc()
|
||||
fields := []zap.Field{
|
||||
zap.Duration("latency", elapsed),
|
||||
zap.Int64("rows", rows),
|
||||
zap.String("sql", sql),
|
||||
}
|
||||
if err != nil {
|
||||
fields = append(fields, zap.Error(err))
|
||||
logs.Error(ctx, "gorm.trace", "SQL执行失败", fields...)
|
||||
return
|
||||
}
|
||||
if elapsed > 200*time.Millisecond {
|
||||
logs.Warn(ctx, "gorm.trace", "慢SQL告警", fields...)
|
||||
return
|
||||
}
|
||||
logs.Debug(ctx, "gorm.trace", "SQL执行", fields...)
|
||||
}
|
||||
|
||||
// NewPostgres 初始化 PostgreSQL 数据库连接
|
||||
func NewPostgres(cfg *config.DatabaseConfig) (*gorm.DB, error) {
|
||||
funcName := "db.NewPostgres"
|
||||
ctx := context.Background()
|
||||
|
||||
logs.Info(ctx, funcName, "正在连接 PostgreSQL",
|
||||
zap.String("host", cfg.Host),
|
||||
zap.Int("port", cfg.Port),
|
||||
zap.String("dbname", cfg.DBName),
|
||||
)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(cfg.DSN()), &gorm.Config{
|
||||
Logger: &zapGormLogger{},
|
||||
})
|
||||
if err != nil {
|
||||
logs.Error(ctx, funcName, "PostgreSQL 连接失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("连接 PostgreSQL 失败: %w", err)
|
||||
}
|
||||
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取底层 sql.DB 失败: %w", err)
|
||||
}
|
||||
|
||||
sqlDB.SetMaxIdleConns(cfg.MaxIdleConns)
|
||||
sqlDB.SetMaxOpenConns(cfg.MaxOpenConns)
|
||||
sqlDB.SetConnMaxLifetime(time.Hour)
|
||||
|
||||
if err := sqlDB.Ping(); err != nil {
|
||||
logs.Error(ctx, funcName, "PostgreSQL Ping 失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("ping PostgreSQL 失败: %w", err)
|
||||
}
|
||||
|
||||
GormDB = db
|
||||
logs.Info(ctx, funcName, "PostgreSQL 连接成功")
|
||||
return db, nil
|
||||
}
|
||||
40
backend/go-service/pkg/db/redis.go
Normal file
40
backend/go-service/pkg/db/redis.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/echochat/backend/config"
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Redis 全局 Redis 客户端实例
|
||||
var Redis *redis.Client
|
||||
|
||||
// NewRedis 初始化 Redis 客户端连接
|
||||
func NewRedis(cfg *config.RedisConfig) (*redis.Client, error) {
|
||||
funcName := "db.NewRedis"
|
||||
ctx := context.Background()
|
||||
|
||||
logs.Info(ctx, funcName, "正在连接 Redis",
|
||||
zap.String("addr", cfg.Addr()),
|
||||
zap.Int("db", cfg.DB),
|
||||
)
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: cfg.Addr(),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
logs.Error(ctx, funcName, "Redis 连接失败", zap.Error(err))
|
||||
return nil, fmt.Errorf("连接 Redis 失败: %w", err)
|
||||
}
|
||||
|
||||
Redis = client
|
||||
logs.Info(ctx, funcName, "Redis 连接成功")
|
||||
return client, nil
|
||||
}
|
||||
26
backend/go-service/pkg/middleware/cors.go
Normal file
26
backend/go-service/pkg/middleware/cors.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORS 跨域中间件
|
||||
// 允许前端跨域访问后端 API
|
||||
func CORS() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, X-Request-ID")
|
||||
c.Header("Access-Control-Expose-Headers", "X-Request-ID")
|
||||
c.Header("Access-Control-Max-Age", "86400")
|
||||
|
||||
if c.Request.Method == http.MethodOptions {
|
||||
c.AbortWithStatus(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
46
backend/go-service/pkg/middleware/logger.go
Normal file
46
backend/go-service/pkg/middleware/logger.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Logger 请求日志中间件
|
||||
// 记录每个请求的完整信息:方法、路径、状态码、耗时、IP、User-Agent
|
||||
// 自动携带 trace_id,慢请求(>500ms)记录 WARN
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
|
||||
c.Next()
|
||||
|
||||
latency := time.Since(start)
|
||||
ctx := c.Request.Context()
|
||||
funcName := "middleware.Logger"
|
||||
|
||||
fields := []zap.Field{
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.Int("status", c.Writer.Status()),
|
||||
zap.Duration("latency", latency),
|
||||
zap.String("ip", c.ClientIP()),
|
||||
zap.String("user_agent", c.Request.UserAgent()),
|
||||
}
|
||||
|
||||
if len(c.Errors) > 0 {
|
||||
fields = append(fields, zap.String("error", c.Errors.String()))
|
||||
logs.Error(ctx, funcName, "请求处理异常", fields...)
|
||||
return
|
||||
}
|
||||
|
||||
if latency > 500*time.Millisecond {
|
||||
logs.Warn(ctx, funcName, "慢请求告警", fields...)
|
||||
return
|
||||
}
|
||||
|
||||
logs.Info(ctx, funcName, "请求完成", fields...)
|
||||
}
|
||||
}
|
||||
36
backend/go-service/pkg/middleware/recovery.go
Normal file
36
backend/go-service/pkg/middleware/recovery.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/echochat/backend/pkg/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Recovery Panic 恢复中间件
|
||||
// 捕获 panic 后记录 ERROR 日志含堆栈信息,返回 500 响应
|
||||
func Recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ctx := c.Request.Context()
|
||||
logs.Error(ctx, "middleware.Recovery", "服务发生 panic",
|
||||
zap.Any("error", r),
|
||||
zap.String("stack", string(debug.Stack())),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("method", c.Request.Method),
|
||||
)
|
||||
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, utils.Response{
|
||||
Code: 500,
|
||||
Message: "服务内部错误",
|
||||
TraceID: logs.GetTraceID(ctx),
|
||||
})
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
26
backend/go-service/pkg/middleware/trace.go
Normal file
26
backend/go-service/pkg/middleware/trace.go
Normal file
@@ -0,0 +1,26 @@
|
||||
// Package middleware 提供 Gin HTTP 中间件
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Trace 链路追踪中间件
|
||||
// 从请求头提取 X-Request-ID,不存在则自动生成
|
||||
// 注入 context,后续所有日志自动携带 trace_id
|
||||
// 在响应头中返回 X-Request-ID
|
||||
func Trace() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
traceID := c.GetHeader("X-Request-ID")
|
||||
if traceID == "" {
|
||||
traceID = logs.GenerateTraceID()
|
||||
}
|
||||
|
||||
ctx := logs.WithTraceID(c.Request.Context(), traceID)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Header("X-Request-ID", traceID)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
91
backend/go-service/pkg/utils/response.go
Normal file
91
backend/go-service/pkg/utils/response.go
Normal file
@@ -0,0 +1,91 @@
|
||||
// Package utils 提供通用工具函数
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/echochat/backend/pkg/logs"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Response 统一 API 响应结构
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
TraceID string `json:"trace_id,omitempty"`
|
||||
Time string `json:"time"`
|
||||
}
|
||||
|
||||
// ResponseOK 成功响应 200
|
||||
func ResponseOK(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, Response{
|
||||
Code: 0,
|
||||
Message: "success",
|
||||
Data: data,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseCreated 创建成功响应 201
|
||||
func ResponseCreated(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusCreated, Response{
|
||||
Code: 0,
|
||||
Message: "created",
|
||||
Data: data,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseBadRequest 参数错误响应 400
|
||||
func ResponseBadRequest(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusBadRequest, Response{
|
||||
Code: 400,
|
||||
Message: message,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseUnauthorized 未认证响应 401
|
||||
func ResponseUnauthorized(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusUnauthorized, Response{
|
||||
Code: 401,
|
||||
Message: message,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseForbidden 无权限响应 403
|
||||
func ResponseForbidden(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusForbidden, Response{
|
||||
Code: 403,
|
||||
Message: message,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseNotFound 资源不存在响应 404
|
||||
func ResponseNotFound(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusNotFound, Response{
|
||||
Code: 404,
|
||||
Message: message,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
|
||||
// ResponseError 服务器内部错误响应 500
|
||||
func ResponseError(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusInternalServerError, Response{
|
||||
Code: 500,
|
||||
Message: message,
|
||||
TraceID: logs.GetTraceID(c.Request.Context()),
|
||||
Time: time.Now().Format("2006-01-02 15:04:05"),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user