← 中文资源

简体中文版本

如何用 Go 构建 HTTP 服务器

构建生产级 Go HTTP 服务器:方法路由、超时、结构化日志、请求体限制、优雅关闭和 httptest 覆盖。

阅读英文原文

引言

Go 标准库足以构建生产 HTTP 服务,但默认 http.Server 没有超时、请求体限制和优雅关闭。这些必须在代码中显式设置。

可测试的 mux

把路由注册封装为返回 http.Handler 的函数,便于用 httptest 测试。使用 Go 1.22+ 的方法和路径模式(如 GET /orders/{id}),通过 r.PathValue 读取参数。

日志与请求体

中间件记录方法、路径、状态和耗时,并生成 request id。用 http.MaxBytesReader 限制请求体,解析 JSON 时使用 DisallowUnknownFields。错误响应保持 JSON 形状稳定。

超时与关闭

设置 ReadHeaderTimeout、ReadTimeout、WriteTimeout 和 IdleTimeout。监听 SIGTERM 后调用 server.Shutdown(ctx),等待进行中请求完成,再关闭数据库连接。

测试

用 httptest.NewServer 或直接调用 handler 测试状态码、JSON 和超时;覆盖 404、方法不允许、超大请求体和取消。真实服务器测试用于验证超时与关闭行为。

常见陷阱

无超时会积累慢连接;在 handler 中启动 goroutine 却不管理生命周期;忽略 Shutdown 返回的错误。生产还应配置 TLS、访问日志和限流。

代码示例

package main

import (
    "encoding/json"
    "errors"
    "net/http"
)

func newHandler() http.Handler {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
        writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
    })

    mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
        id := r.PathValue("id")
        if id == "" {
            writeJSON(w, http.StatusBadRequest, map[string]string{"error": "missing id"})
            return
        }
        writeJSON(w, http.StatusOK, map[string]string{"id": id})
    })

    return mux
}

func writeJSON(w http.ResponseWriter, status int, value any) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(status)
    _ = json.NewEncoder(w).Encode(value)
}
type statusRecorder struct {
    http.ResponseWriter
    status int
    bytes  int
}

func (r *statusRecorder) WriteHeader(status int) {
    r.status = status
    r.ResponseWriter.WriteHeader(status)
}

func (r *statusRecorder) Write(p []byte) (int, error) {
    if r.status == 0 {
        r.status = http.StatusOK
    }
    n, err := r.ResponseWriter.Write(p)
    r.bytes += n
    return n, err
}
func logging(logger *slog.Logger, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        rec := &statusRecorder{ResponseWriter: w}
        next.ServeHTTP(rec, r)

        status := rec.status
        if status == 0 {
            status = http.StatusOK
        }
        logger.Info("request",
            "method", r.Method,
            "path", r.URL.Path,
            "status", status,
            "bytes", rec.bytes,
            "duration", time.Since(start),
        )
    })
}
func limitBody(max int64, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        r.Body = http.MaxBytesReader(w, r.Body, max)
        next.ServeHTTP(w, r)
    })
}
server := &http.Server{
    Addr:              ":8080",
    Handler:           logging(logger, limitBody(1<<20, newHandler())),
    ReadHeaderTimeout: 5 * time.Second,
    ReadTimeout:       10 * time.Second,
    WriteTimeout:      15 * time.Second,
    IdleTimeout:       60 * time.Second,
    MaxHeaderBytes:    1 << 20,
}
func withTimeout(d time.Duration, next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithTimeout(r.Context(), d)
        defer cancel()
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}
func run() error {
    logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
    server := &http.Server{
        Addr:              ":8080",
        Handler:           logging(logger, limitBody(1<<20, newHandler())),
        ReadHeaderTimeout: 5 * time.Second,
        ReadTimeout:       10 * time.Second,
        WriteTimeout:      15 * time.Second,
        IdleTimeout:       60 * time.Second,
    }

    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    errCh := make(chan error, 1)
    go func() {
        errCh <- server.ListenAndServe()
    }()

    select {
    case err := <-errCh:
        if !errors.Is(err, http.ErrServerClosed) {
            return err
        }
        return nil
    case <-ctx.Done():
        shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
        defer cancel()
        if err := server.Shutdown(shutdownCtx); err != nil {
            return fmt.Errorf("shutdown: %w", err)
        }
        if err := <-errCh; !errors.Is(err, http.ErrServerClosed) {
            return err
        }
        return nil
    }
}
func TestHealth(t *testing.T) {
    req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
    rec := httptest.NewRecorder()

    newHandler().ServeHTTP(rec, req)

    if rec.Code != http.StatusOK {
        t.Fatalf("status = %d, want 200", rec.Code)
    }
    if got := rec.Header().Get("Content-Type"); got != "application/json" {
        t.Fatalf("content-type = %q", got)
    }
}

配套在线工具