本文介绍了如何将gorilla mux与http.TimeoutHandler一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我通过创建一个新的路由器, gorillaMux:= mux.NewRouter() 通过像> gorillaMux.HandleFunc(/,rootHandler) code> 我通过 server:=& http.Server {Addr::1234}创建服务器和 server.ListenAndServe()
I create a new Router by gorillaMux := mux.NewRouter()
add my routes by calls like gorillaMux.HandleFunc("/", rootHandler)
I create the server by server := &http.Server{Addr:":1234"} and server.ListenAndServe()
在go中写入的HTTP服务器中,我使用大猩猩/多路复用器进行路由, > 我想使用 http.TimeoutHandler (和/或其他中间件),但我无法理解我可以在哪里适合它们。
In an HTTP server written in go, I use gorilla/mux for routing, I want to use http.TimeoutHandler (and/or other "middleware") but I can't understand where I can fit them.
为了说清楚:
To make it clear:
在哪里可以插入 http.TimeoutHandler 或任何其他中间件?
Where can I insert the http.TimeoutHandler or any other middleware for that matter?
推荐答案可以这样做:
Here is how you can do this:
package main import ( "fmt" "github/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处理程序,您可以将它们堆叠在一起:
If you have more than one HTTP handler, you can stack them up:
// this is quite synthetic and ugly example, but it illustrates how Handlers works muxWithMiddlewares := http.StripPrefix("/api", http.TimeoutHandler(mux, time.Second*3, "Timeout!"))更多推荐
如何将gorilla mux与http.TimeoutHandler一起使用
发布评论