Files
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

92 lines
2.4 KiB
Go

// Package handler 提供 HTTP 入口,只做参数解析 / 序列化 / 错误码映射,
//不写业务逻辑。所有业务计算都走 service 层。
package handler
import (
"errors"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/kennethcheng/fuellog-api/pkg/apperror"
)
// writeError 把任意 error 渲染成统一 JSON 响应 + 对应 HTTP 状态码。
// 已知 *apperror.Error 用其 HTTPStatus,其它归 500 + INTERNAL。
func writeError(c *gin.Context, err error) {
if appErr, ok := apperror.As(err); ok {
c.JSON(appErr.HTTPStatus(), gin.H{
"code": appErr.Code,
"message": appErr.Message,
})
return
}
// gin-validator 抛的 binding 错误
if isValidationErr(err) {
c.JSON(http.StatusBadRequest, gin.H{
"code": apperror.CodeInvalidArg,
"message": err.Error(),
})
return
}
c.JSON(http.StatusInternalServerError, gin.H{
"code": apperror.CodeInternal,
"message": "服务器开了小差,请稍后再试",
})
}
func isValidationErr(err error) bool {
if err == nil {
return false
}
// 走错误信息启发式判断;真正严谨的做法是导入 validator/types
// 引入额外依赖不划算,Phase 2 内部接口稳定后切换
msg := err.Error()
return containsAny(msg, []string{"validation", "Field validation", "required", "invalid"})
}
func containsAny(s string, subs []string) bool {
for _, sub := range subs {
if len(sub) <= len(s) {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
}
}
return false
}
// parseUint64 解析路径里的 uint64 id。失败返 INVALID_ARGUMENT。
func parseUint64(c *gin.Context, key string) (uint64, error) {
raw := c.Param(key)
v, err := strconv.ParseUint(raw, 10, 64)
if err != nil || v == 0 {
return 0, apperror.New(apperror.CodeInvalidArg, "无效的 id: "+raw)
}
return v, nil
}
// bindJSON 把请求体解析到 dst;validator 失败自动转为 INVALID_ARGUMENT。
func bindJSON(c *gin.Context, dst any) error {
if err := c.ShouldBindJSON(dst); err != nil {
return apperror.Wrap(apperror.CodeInvalidArg, "请求体不合法: "+err.Error(), err)
}
return nil
}
// sendJSON 统一回写 200。
func sendJSON(c *gin.Context, data any) {
c.JSON(http.StatusOK, data)
}
// errBind 内部错误快速生成函数(减少模板代码)。
func errBind(err error) error {
if err == nil {
return nil
}
return apperror.Wrap(apperror.CodeInvalidArg, err.Error(), errors.Unwrap(err))
}