1 回答
TA贡献1943条经验 获得超7个赞
立即响应使用 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
}
}
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报