Commit Graph
2 Commits
Author SHA1 Message Date
KennethCheng bfa0d76222 feat(backend): 接入 HTTP handler、router、main 装配,端到端冒烟全通
Phase 1.3b。Phase 1.3a 留的 service 现在有了 HTTP 入口,curl 能跑通完整的
"建车 → 加三次油 → 看统计 → 删记录 → 删车"全链路,核心计算命中 plan §6。

新增:
- internal/handler/common.go  通用:writeError / parseUint64 / bindJSON / sendJSON
  * 统一错误格式:{ "code": "INVALID_ARGUMENT|NOT_FOUND|...", "message": "..." }
  * parseUint64 自动把非数字 / 0 翻成 INVALID_ARGUMENT
  * bindJSON 把 gin-validator 错误也归到 INVALID_ARGUMENT
- internal/handler/errors.go   errInvalid / errInvalidVehicleID 等小工具
- internal/handler/vehicle.go  CRUD + SetDefault 六个端点
- internal/handler/refuel_record.go  CRUD + List(?vehicle_id) + Statistics
- internal/router/router.go    把所有 /api 路由挂上 Gin engine

main.go 改动:
- 引入 wire():repository → service → handler 一气串好
- /api 业务路由从 router.Build 注入
- /health 与 NoRoute 保持原状

scripts/smoke.ps1 端到端冒烟脚本(13 步):
  health → list → create vehicle → list → refuel×3(其中 1 个半箱)→
  statistics → list refuels → delete refuel → statistics 刷新 →
  delete vehicle → GET 404

核心计算命中 plan §6.3 / §19:
  320/40 = 8.0  (price_per_liter)        ✓
  256/32 = 8.0  (price_per_liter)        ✓
  32/(11000-10500)*100 = 6.4  (L/100km)  ✓
  256/500 = 0.512  (元/公里)              ✓
  半箱油(11200/10L/is_full=false)不进入标准油耗采样 ✓
  删除记录后 avg_consumption / cost_per_km 立即重算 ✓

期间踩到的两个坑(都修了):
  1) handler 用 []struct{}{} 试图给 []model.Vehicle / []model.RefuelRecord
     兜空数组,Go 强类型不接受;改用 []model.Vehicle{} 即可
  2) Statistics 列表按 refuel_time DESC 返回,正向迭代会让 mileage 算成负数
     (newer - older < 0);改成倒序迭代,prevFull 总是更老的那次

未做(留给后续):
- 单元测试(下一步 Phase 1.4 独立 commit)
- 显式 migration 文件(下次 schema 变更补;此次仍 AutoMigrate 兜底)
- Dashboard / 统计更复杂的 endpoint(基础 Statistics 已可用)
- PWA / 导入导出 / Docker(留给 Phase 1.5+)

验证:
  go vet ./...   0 issues
  go build       26 MB binary
  smoke.ps1      13/13 断言通过
2026-09-13 16:13:25 +08:00
KennethCheng ca9831a050 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.
2026-09-13 15:55:58 +08:00