在用go编写的HTTP服务器中,我使用gorilla/mux进行路由,
我想使用http.TimeoutHandler
(和/或其他“中间件”),但我无法理解我可以适应它们的位置。
说清楚:
gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", rootHandler)
server := &http.Server{Addr:":1234"}
和server.ListenAndServe()
我可以在哪里插入http.TimeoutHandler
或任何其他中间件?
答案 0 :(得分:10)
以下是如何执行此操作的方法:
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!"))
答案 1 :(得分:1)
此解决方案未回答使用TimeoutHandler。我在这里发布这个以防任何人想要对其服务器超时进行细粒度控制。如果需要,此替代方法将允许定义IdleTimeout和RequestHeaderTimeout。我在这个例子中使用gorilla / mux和gorilla / handlers。希望它有所帮助。
// ReadTimeout is a timing constraint on the client http request imposed by the server from the moment
// of initial connection up to the time the entire request body has been read.
// [Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]
// WriteTimeout is a time limit imposed on client connecting to the server via http from the
// time the server has completed reading the request header up to the time it has finished writing the response.
// [Accept] --> [TLS Handshake] --> [Request Headers] --> [Request Body] --> [Response]
func main() {
mux := router.EpicMux()
srv := &http.Server{
Handler: handlers.LoggingHandler(os.Stdout, mux),
Addr: "localhost:8080",
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
func EpicMux() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/", BaseURLRouter).Methods(http.MethodGet)
// create the subroutes for v1 and v2
v1 := r.PathPrefix("api/v1").Subrouter()
// register handlers to appropriate version
v1.HandleFunc("/person", PersonHandlerV1).Methods(http.MethodPost)
v2 := r.PathPrefix("api/v2").Subrouter()
v2.HandleFunc("/person", PersonHandlerV2).Methods(http.MethodPost)
return r
}