← 中文资源

简体中文版本

可组合的 HTTP 中间件链

通过包装下一个处理函数的中间件组合 HTTP 处理器,统一加入日志、恢复与请求标识而无需重复代码。

阅读英文原文

实现说明

除了函数 chain、logging、recoverPanic,文件里再无其他定义。 重复被限制在 for i := len(middleware) - 1; i >= 0; i-- 里——其余代码按顺序各跑一遍。无论函数体里发生什么,defer 的调用都会在离开时最后执行。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 全部导入都来自标准库:log、net/http、time。 文件在加载时定义 chain、logging、recoverPanic。

入口签名:func chain(h http.Handler, middleware ...Middleware) http.Handler

核心语句

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	next.ServeHTTP(w, r)
	log.Printf("method=%s path=%s duration=%s", r.Method, r.URL.Path, time.Since(start))
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if rec := recover(); rec != nil {
			http.Error(w, "internal error", http.StatusInternalServerError)
		}
	}()
	next.ServeHTTP(w, r)
})
func chain(h http.Handler, middleware ...Middleware) http.Handler {
	for i := len(middleware) - 1; i >= 0; i-- {
		h = middleware[i](h)
	}
	return h
}

代码示例

package main

import (
	"log"
	"net/http"
	"time"
)

type Middleware func(http.Handler) http.Handler

func chain(h http.Handler, middleware ...Middleware) http.Handler {
	for i := len(middleware) - 1; i >= 0; i-- {
		h = middleware[i](h)
	}
	return h
}

func logging(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()
		next.ServeHTTP(w, r)
		log.Printf("method=%s path=%s duration=%s", r.Method, r.URL.Path, time.Since(start))
	})
}

func recoverPanic(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if rec := recover(); rec != nil {
				http.Error(w, "internal error", http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}