一、前言
本文我们来探讨下 如何设置http服务端服务的执行超时时间
三、设置处理器超时时间
func sayHelloTimeout(w http.ResponseWriter, r *http.Request) {
fmt.Println("path", r.URL.Path)
fmt.Println(w, "hello world")
time.Sleep(5 * time.Second)
w.Write([]byte("hello word"))
}
func main() {
//1. 创建http请求处理注册器
handler := http.NewServeMux()
//2.注册处理器,并设置handler超时时间
handler.Handle("/helloTimeout", http.TimeoutHandler(http.HandlerFunc(sayHelloTimeout), time.Second*3, ""))
//3. 创建httpserver
server := &http.Server{Addr: ":9090", Handler: handler}
//4. 启动http服务
err := server.ListenAndServe()
if err != nil {
panic(err)
}
}
如上代码2,使用http.TimeoutHandler设置处理器sayHelloTimeout的超时时间为3s,然后我们在sayHelloTimeout的实现内休眠5s是为模拟处理器耗时为5s。
因为处理器耗时为5s,我们设置超时时间为3s,所以服务端会发现处理超时,就会返回给客户端503错