← 返回 Golang 列表

Go HTTP 服务器与中间件

net/http 构建 REST API,中间件链处理日志、认证与恢复。

中间件定义

type Middleware func(next http.Handler) http.Handler

func Logging(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    log.Printf("%s %s", r.Method, r.URL.Path)
    next.ServeHTTP(w, r)
  })
}

链式注册

mux := http.NewServeMux()
mux.Handle("/", Logging(http.HandlerFunc(home)))
http.ListenAndServe(":8080", mux)