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