我正在使用具有Web服务器的Go应用。我试图添加超时,遇到一个问题。这是我制作的示例代码,因为不可能发布实际代码:
package main
import (
"fmt"
"html/template"
"net/http"
"time"
)
var layout *template.Template
func main() {
router := http.NewServeMux()
server := &http.Server{
Addr: ":8888",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 1 * time.Second,
IdleTimeout: 15 * time.Second,
}
router.HandleFunc("/", home)
var err error
layout, err = template.ParseFiles("./layout.html")
if err != nil {
fmt.Printf("Error1: %+v\n", err)
}
server.ListenAndServe()
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Println("responding")
err := layout.Execute(w, template.HTML(`World`))
if err != nil {
fmt.Printf("Error2: %+v\n", err)
}
time.Sleep(5 * time.Second)
}
layout.html: Hello {{.}}!
当我运行它并访问127.0.0.1:8888时,浏览器将保持加载状态,并且触发超时的home()
会重新启动,并在停止之前执行10次,并且浏览器显示一个连接重置错误。
我希望超时后,函数将立即结束,连接将关闭,浏览器将停止加载并显示错误。
我该如何实现?
答案 0 :(得分:0)
立即使用goroutine和上下文超时进行响应
package main
import (
"context"
"fmt"
"html/template"
"net/http"
"time"
)
var layout *template.Template
var WriteTimeout = 1 * time.Second
func main() {
router := http.NewServeMux()
server := &http.Server{
Addr: ":8889",
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: WriteTimeout + 10*time.Millisecond, //10ms Redundant time
IdleTimeout: 15 * time.Second,
}
router.HandleFunc("/", home)
server.ListenAndServe()
}
func home(w http.ResponseWriter, r *http.Request) {
fmt.Printf("responding\n")
ctx, _ := context.WithTimeout(context.Background(), WriteTimeout)
worker, cancel := context.WithCancel(context.Background())
var buffer string
go func() {
// do something
time.Sleep(2 * time.Second)
buffer = "ready all response\n"
//do another
time.Sleep(2 * time.Second)
cancel()
fmt.Printf("worker finish\n")
}()
select {
case <-ctx.Done():
//add more friendly tips
w.WriteHeader(http.StatusInternalServerError)
return
case <-worker.Done():
w.Write([]byte(buffer))
fmt.Printf("writed\n")
return
}
}