把全部逻辑塞进 handler 的代码能跑,但没法测、没法复用、改一处动全身。下面是一个只用标准库的骨架:分层与依赖方向、路由与超时、中间件、优雅关闭、结构化日志与配置,Go 1.22+ 为准。
分层与目录结构 目录 :cmd/api/main.go(组装:配置、依赖、路由、优雅关闭)+ internal/post/(handler.go / service.go / repo_memory.go / model.go)。
handler:解析参数、最小校验、调 service、序列化响应;不写业务规则、不碰 SQL。 service:业务逻辑与事务边界,错误用哨兵值表达;repository 的接口定义在使用方 (service),内存实现与 Postgres 实现都去满足它。 repository:只做数据存取与映射;换存储、写内存实现都不用改 service。 HTTP 层 1 2 3 4 5 6 7 8 9 10 11 12 13 14 func (h *Handler) Create(w http.ResponseWriter, r *http.Request) { var req struct { Title string `json:"title"` } if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1 <<20 )).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, "invalid_json" , "请求体不是合法 JSON" ) return } p, err := h.svc.Create(r.Context(), req.Title) if err != nil { writeError(w, statusOf(err), codeOf(err), messageOf(err)) return } w.WriteHeader(http.StatusCreated) _ = json.NewEncoder(w).Encode(p) }
业务与存储层 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 type Repository interface { Insert(ctx context.Context, p Post) (Post, error ) } type Service struct { repo Repository }type MemoryRepo struct { mu sync.Mutex; items []Post } func (s *Service) Create(ctx context.Context, title string ) (Post, error ) { if title = strings.TrimSpace(title); title == "" { return Post{}, fmt.Errorf("%w: title 为空" , ErrInvalidInput) } return s.repo.Insert(ctx, Post{Title: title}) } func (m *MemoryRepo) Insert(_ context.Context, p Post) (Post, error ) { m.mu.Lock(); defer m.mu.Unlock() m.items = append (m.items, p) return p, nil }
路由、组装与超时 1 2 3 4 5 6 7 8 9 10 11 12 13 func main () { logger := slog.New(slog.NewJSONHandler(os.Stdout, nil )) h := &Handler{svc: NewService(&MemoryRepo{})} mux := http.NewServeMux() mux.HandleFunc("POST /posts" , h.Create) mux.HandleFunc("GET /posts/{id}" , h.Get) srv := &http.Server{ Handler: Recover(logger)(Logger(logger)(RequestID(mux))), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 20 * time.Second, } }
中间件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 func RequestID (next http.Handler) http.Handler { return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), idKey{}, newID()))) }) } func Logger (log *slog.Logger, next http.Handler) http.Handler { return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { start, sw := time.Now(), &statusWriter{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(sw, r) log.Info("request" , "method" , r.Method, "status" , sw.status, "dur" , time.Since(start)) }) } func Recover (log *slog.Logger, next http.Handler) http.Handler { return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { defer func () { if v := recover (); v != nil { log.Error("panic" , "value" , v, "stack" , string (debug.Stack())) http.Error(w, "internal error" , http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) }
优雅关闭 1 2 3 4 5 6 7 8 9 10 11 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM); defer stop() go func () { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { logger.Error("listen" , "err" , err) } }() <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 10 *time.Second); defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { logger.Error("shutdown" , "err" , err) }
日志、校验、配置与注意事项 log/slog(Go 1.21+)的 logger 注入 handler 与 service,不要用全局 logger;测试里换成写 buffer 的 handler 即可断言。配置只从环境变量或配置中心读,启动时集中校验,连接串与密钥不写进代码与镜像。四个超时默认值都是 0(无限等待),ReadHeaderTimeout 为 0 时回退用 ReadTimeout;不设超时会被慢连接持续占住 goroutine 与连接,是最常见的资源耗尽来源。 校验分两层:格式问题(JSON 不合法、字段缺失)在 handler 返回 400,业务规则问题在 service 返回哨兵错误 映射成 422;内部错误只记日志,返回客户端的公开文案不包含 DB 报错原文。 分层是依赖方向不是目录数量,事务边界在 service;http.ServeMux 的模式冲突在注册时 panic,要在启动阶段暴露;srv.Close() 会直接掐断在途请求,只能作超时兜底。