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:
2026-09-13 15:55:58 +08:00
parent a0c2701cf1
commit ca9831a050
22 changed files with 550 additions and 0 deletions
+122
View File
@@ -0,0 +1,122 @@
// Command server 是 FuelLog API 入口。
//
// 启动流程:
// 1. 加载 .env
// 2. 解析配置
// 3. 初始化数据库(Phase 2 起接 GORM)
// 4. 装配路由
// 5. 监听并优雅退出
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/kennethcheng/fuellog-api/internal/config"
"github.com/kennethcheng/fuellog-api/internal/middleware"
"github.com/kennethcheng/fuellog-api/pkg/apperror"
)
func main() {
// .env 加载失败不致命(可能是生产环境用环境变量注入)
if err := godotenv.Load(); err != nil && !os.IsNotExist(err) {
slog.Warn(".env load failed", "err", err)
}
cfg, err := config.Load()
if err != nil {
slog.Error("config load failed", "err", err)
os.Exit(1)
}
gin.SetMode(cfg.GinMode)
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: parseLogLevel(cfg.LogLevel),
})))
app := &application{cfg: cfg}
srv := &http.Server{
Addr: cfg.ServerAddr,
Handler: app.router(),
ReadHeaderTimeout: 10 * time.Second,
}
// 启动 + 优雅退出
go func() {
slog.Info("server starting", "addr", cfg.ServerAddr, "mode", cfg.GinMode)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Error("server error", "err", err)
os.Exit(1)
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
slog.Info("server shutting down")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
slog.Error("graceful shutdown failed", "err", err)
os.Exit(1)
}
slog.Info("server stopped")
}
// application 持有所有依赖,避免散落全局变量。
type application struct {
cfg *config.Config
}
// router 构建并返回 Gin 引擎。
// 当前阶段只暴露 /health;Phase 2 起逐步接 /api/vehicles、/api/refuels。
func (a *application) router() *gin.Engine {
r := gin.New()
r.Use(
middleware.Recover(),
middleware.Logger(),
middleware.CORS(a.cfg.CORSOrigins),
)
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"code": apperror.CodeNotFound,
"message": "路径不存在: " + c.Request.URL.Path,
})
})
r.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"time": a.cfg.Now().In(a.cfg.Location()).Format(time.RFC3339),
})
})
// /api 路由组(Phase 2 起在此挂载业务路由)
api := r.Group("/api")
_ = api // 占位,避免未使用告警
return r
}
func parseLogLevel(s string) slog.Level {
switch s {
case "debug":
return slog.LevelDebug
case "warn":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}