Z
ZHANK
Web 与工程化

net/http 进阶

ServeMux 路由、中间件模式、静态文件、自定义 Handler

net/http 进阶

Go 标准库 net/http 本身就足够强大——ServeMux 路由、中间件模式、自定义 Handler。

学完本章你将: 掌握 ServeMux 路由、中间件模式、自定义 Handler。


ServeMux 路由

go
package main

import (
    "fmt"
    "net/http"
)

func main() {
    mux := http.NewServeMux()

    // 路由注册
    mux.HandleFunc("/", homeHandler)
    mux.HandleFunc("/users", usersHandler)
    mux.HandleFunc("GET /users/{id}", userHandler)  // Go 1.22+ 方法+路径参数

    http.ListenAndServe(":8080", mux)
}

func userHandler(w http.ResponseWriter, r *http.Request) {
    id := r.PathValue("id")  // Go 1.22+ 获取路径参数
    fmt.Fprintf(w, "User ID: %s", id)
}

中间件模式

go
// 中间件类型
type Middleware func(http.Handler) http.Handler

// 日志中间件
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        next.ServeHTTP(w, r)
        fmt.Printf("%s %s %v\n", r.Method, r.URL.Path, time.Since(start))
    })
}

// 链式组合
func chain(h http.Handler, middlewares ...Middleware) http.Handler {
    for i := len(middlewares) - 1; i >= 0; i-- {
        h = middlewares[i](h)
    }
    return h
}

// 使用
handler := chain(mux, loggingMiddleware, authMiddleware)
http.ListenAndServe(":8080", handler)