http.TimeoutHandler
不是讓會話在某段時間後過期。相反,它用於限制處理程序的執行時間,即如果給定時間已過,它將返回503 Service Unavailable
給HTTP客戶端。下面是這種用法的一個例子:
func handlerNoTimeout(w http.ResponseWriter, r *http.Request) {
//This handler takes 1 second to finished, won't timeout
time.Sleep(1 * time.Second)
w.Write([]byte("Handler OK"))
}
func handlerTimeout(w http.ResponseWriter, r *http.Request) {
//This handler takes 4 seconds to finished.
//Before finished, it will timeout,
//503 response will be sent to client + given message (i.e. Timeout!)
time.Sleep(4 * time.Second)
w.Write([]byte("Handler timeout (never executed)"))
}
func main() {
mux := http.NewServeMux()
rh := http.RedirectHandler("http://10.130.0.10:820/login", 307)
mux.Handle("/", rh)
mux.HandleFunc("/timeout", handlerTimeout)
mux.HandleFunc("/notimeout", handlerNoTimeout)
tmux := http.TimeoutHandler(mux, time.Second*3, "Timeout!")
go http.ListenAndServe(":818", tmux)
go http.ListenAndServeTLS(":821", "server.pem", "server.key", tmux)
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
如果您的接入/timeout
,你會得到503
與超時消息,但如果你訪問/notimeout
,HTTP響應將是200 OK
。
會話是的狀態服務器存儲,不處理步驟/任務/作業這可能需要一段時間來完成。除非您在後臺定義了一個函數/方法/處理程序,否則會話將不會過期,並定期查看會話創建時間,如果經過一段時間,則將其標記爲已過期。
在您的代碼中,如果重定向處理程序(即登錄處理程序)需要超過3秒,它將會超時。
你有沒有試過看看如果在goroutine裏面沒有運行ListenAndServe時項目超時?要測試註釋掉ListenAndServeTLS,運行ListenAndServe而不啓動單獨的例程。 – reticentroot