拦截器是一种设计模式,允许在方法执行前后插入自定义行为,在 go 中可以通过 net/http 中间件实现。它具有可扩展性、可重用性、可测试性等优点,可用于身份验证、授权、缓存、日志记录和自定义错误处理等场景。
揭秘 Golang 中的拦截器机制
简介
拦截器是一种设计模式,它允许在执行方法之前或之后插入自定义行为。在 Go 中,拦截器可以通过编写 net/http
中间件实现。
具体实现
以下是一个使用 net/http
编写拦截器的示例:
package main import ( "fmt" "log" "net/http" ) func main() { // 创建一个新的中间件函数 logMiddleware := func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Println("Request received:", r.URL.Path) // 调用下一个处理程序 next.ServeHTTP(w, r) }) } // 创建一个新的 HTTP 处理程序 mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") }) // 将中间件应用到处理程序 http.Handle("/", logMiddleware(mux)) // 启动 HTTP 服务器 log.Println("Listening on port 8080") http.ListenAndServe(":8080", nil) }