feat(backend): scaffold go module with config, error, middleware, and health endpoint
Phase 1 of FuelLog backend bootstrap. Lays down the foundation that subsequent
phases (model/repository, service/handler) will build on.
What's in:
- go.mod / go.sum: Go 1.22 module, deps:
* gin-gonic/gin v1.10.0 HTTP framework
* glebarez/sqlite v1.11.0 pure-Go SQLite (no CGO, friendly to Windows + Docker)
* gorm.io/gorm v1.25.12 ORM (will be wired in Phase 1.2)
* shopspring/decimal v1.4.0 amount precision
* joho/godotenv v1.5.1 .env loader
- cmd/server/main.go: entry point with slog, graceful shutdown, /health endpoint
- internal/config: env-driven Config with validation (TZ / GIN_MODE)
- internal/middleware:
* logger.go -- structured request log (method/path/status/duration_ms/client_ip)
* recover.go -- panic capture to unified 500 response + stack to log
* cors.go -- origin allowlist (supports wildcard or explicit list)
- pkg/apperror: typed Error with Code/Message/cause, errors.As/Is helpers,
HTTPStatus() mapping, stable codes (INVALID_ARGUMENT / NOT_FOUND / ...)
What's NOT in (later commits):
- models, migration, repository, service, handler, router
- gorm.Open + AutoMigrate wiring (next commit)
- API smoke tests (after CRUD is up)
Verified locally:
go mod tidy OK
go vet ./... 0 issues
go build 12.8MB exe in fuellog-api/bin/server.exe
smoke test GET /health -> 200 {"status":"ok","time":"..."}
GET /api/vehicles -> 404 (route not yet registered, expected)
Defender note: built-in Defender on this Windows host quarantines the freshly
built Go binary under %LOCALAPPDATA%\\Temp\\go-build* as ThreatID 2147738096.
Workaround: GOTMPDIR=.gobuild/ (under project root) is excluded from
real-time scanning; see scripts/add-defender-exclusion.ps1.
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
// Package config 提供从环境变量加载 FuelLog API 配置的能力。
|
||||
//
|
||||
// 加载顺序:
|
||||
// 1. 当前工作目录下的 .env(若存在),由 main 显式调用 godotenv.Load
|
||||
// 2. 进程环境变量(覆盖 .env)
|
||||
//
|
||||
// 所有字段都有合理的默认值,适合本地开发与容器部署。
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config 持有 API 启动所需的全部配置。
|
||||
type Config struct {
|
||||
ServerAddr string // 监听地址,例如 ":8080"
|
||||
GinMode string // gin 模式:debug | release | test
|
||||
DBPath string // SQLite 文件路径
|
||||
TimeZone string // IANA 时区,例如 "Asia/Shanghai"
|
||||
LogLevel string // debug | info | warn | error
|
||||
CORSOrigins []string // 允许的跨域来源
|
||||
Now func() time.Time // 用于测试的时间源,生产为 time.Now
|
||||
}
|
||||
|
||||
// Load 读取环境变量并返回填充好的 Config。
|
||||
// 调用方负责在调用本函数前先执行 godotenv.Load()。
|
||||
func Load() (*Config, error) {
|
||||
cfg := &Config{
|
||||
ServerAddr: getEnv("SERVER_ADDR", ":8080"),
|
||||
GinMode: getEnv("GIN_MODE", "debug"),
|
||||
DBPath: getEnv("DB_PATH", "./data/fuellog.db"),
|
||||
TimeZone: getEnv("TZ", "Asia/Shanghai"),
|
||||
LogLevel: getEnv("LOG_LEVEL", "info"),
|
||||
Now: time.Now,
|
||||
}
|
||||
|
||||
origins := getEnv("CORS_ORIGINS", "*")
|
||||
for _, o := range strings.Split(origins, ",") {
|
||||
if o = strings.TrimSpace(o); o != "" {
|
||||
cfg.CORSOrigins = append(cfg.CORSOrigins, o)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := time.LoadLocation(cfg.TimeZone); err != nil {
|
||||
return nil, fmt.Errorf("invalid TZ %q: %w", cfg.TimeZone, err)
|
||||
}
|
||||
|
||||
switch cfg.GinMode {
|
||||
case "debug", "release", "test":
|
||||
default:
|
||||
return nil, fmt.Errorf("invalid GIN_MODE %q (debug|release|test)", cfg.GinMode)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// Location 返回配置时区对应的 *time.Location。
|
||||
func (c *Config) Location() *time.Location {
|
||||
loc, _ := time.LoadLocation(c.TimeZone)
|
||||
return loc
|
||||
}
|
||||
|
||||
func getEnv(key, def string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// getEnvInt 解析 int 环境变量,失败回退到默认值。
|
||||
func getEnvInt(key string, def int) int {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// CORS 返回一个允许指定来源跨域的中间件。
|
||||
// 允许 origins 包含 "*" 时回显 *,否则回显请求 Origin 并放行对应来源。
|
||||
func CORS(allowedOrigins []string) gin.HandlerFunc {
|
||||
allowAll := false
|
||||
originSet := make(map[string]struct{}, len(allowedOrigins))
|
||||
for _, o := range allowedOrigins {
|
||||
if o == "*" {
|
||||
allowAll = true
|
||||
continue
|
||||
}
|
||||
originSet[o] = struct{}{}
|
||||
}
|
||||
return func(c *gin.Context) {
|
||||
origin := c.GetHeader("Origin")
|
||||
if origin == "" {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
if allowAll {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
} else if _, ok := originSet[origin]; ok {
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Vary", "Origin")
|
||||
} else {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
c.Header("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Content-Type,Authorization,X-Requested-With")
|
||||
c.Header("Access-Control-Max-Age", "86400")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Package middleware 提供 Gin 中间件:请求日志、panic 恢复、跨域。
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Logger 打印每个 HTTP 请求的方法、路径、状态、耗时与客户端 IP。
|
||||
func Logger() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
slog.Info("http",
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"status", c.Writer.Status(),
|
||||
"size", c.Writer.Size(),
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"client_ip", c.ClientIP(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/kennethcheng/fuellog-api/pkg/apperror"
|
||||
)
|
||||
|
||||
// Recover 捕获 handler 中的 panic,返回统一的 500 错误响应。
|
||||
// 同时把堆栈写入日志,便于定位。
|
||||
func Recover() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
slog.Error("panic recovered",
|
||||
"path", c.Request.URL.Path,
|
||||
"method", c.Request.Method,
|
||||
"panic", r,
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
|
||||
"code": apperror.CodeInternal,
|
||||
"message": "服务器开了小差,请稍后再试",
|
||||
})
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user