面试题答案
一键面试常见方式
在Go中实现HTTP中间件常见方式是利用函数的闭包特性。HTTP处理函数类型为 http.HandlerFunc
,可以通过定义一个高阶函数,该高阶函数接收一个 http.Handler
或 http.HandlerFunc
作为参数,返回一个新的 http.Handler
。这个新的 http.Handler
在调用原始的 http.Handler
前后添加额外的逻辑,以此实现中间件功能。
示例代码
package main
import (
"fmt"
"net/http"
"time"
)
// loggingMiddleware 记录请求时间的中间件
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// 调用下一个处理器
next.ServeHTTP(w, r)
elapsed := time.Since(start)
fmt.Printf("Request %s %s took %s\n", r.Method, r.URL.Path, elapsed)
})
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
}
func main() {
// 使用中间件包装处理器
http.Handle("/", loggingMiddleware(http.HandlerFunc(helloHandler)))
// 启动HTTP服务器
fmt.Println("Server is listening on :8080")
http.ListenAndServe(":8080", nil)
}
在上述代码中,loggingMiddleware
是一个中间件函数,它接收一个 http.Handler
作为参数并返回一个新的 http.Handler
。新的 http.Handler
在处理请求前记录开始时间,处理请求后记录结束时间并打印请求的方法、路径和耗时。helloHandler
是一个简单的HTTP处理函数,main
函数中使用 loggingMiddleware
包装了 helloHandler
,并启动了HTTP服务器。