在用go编写的HTTP服务器中,我使用大猩猩/多路复用器进行路由, 我想使用http.TimeoutHandler(和/或其他“中间件”),但我不知道该在哪里放置它们。
http.TimeoutHandler
明确说明:
gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", rootHandler)
server := &http.Server{Addr:":1234"}
server.ListenAndServe()
http.TimeoutHandler为此,我可以在哪里插入或任何其他中间件?
这是您可以执行的操作:
package main import ( "fmt" "github.com/gorilla/mux" "net/http" "time" ) func rootHandler(w http.ResponseWriter, r *http.Request) { time.Sleep(5 * time.Second) fmt.Fprintf(w, "Hello!") } func main() { mux := mux.NewRouter() mux.HandleFunc("/", rootHandler) muxWithMiddlewares := http.TimeoutHandler(mux, time.Second*3, "Timeout!") http.ListenAndServe(":8080", muxWithMiddlewares) }
如果您有多个HTTP处理程序,则可以将它们堆叠起来:
// this is quite synthetic and ugly example, but it illustrates how Handlers works muxWithMiddlewares := http.StripPrefix("/api", http.TimeoutHandler(mux, time.Second*3, "Timeout!"))