我是Go程序員的新手。我正在編寫一個Web應用程序,我需要服務器等待活動請求發出后再關閉。我寫了一個處理程序,等待5秒鐘回答。如果我發出請求并停止服務器(在5秒鐘之前),則會收到“無法連接”錯誤。有沒有一種方法可以停止監聽新請求并等待活動請求完成?這是我的例子func main() { log.Infof("Starting (PID %d)...", os.Getpid()) stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGTERM) signal.Notify(stop, syscall.SIGINT) listenAt := "127.0.0.1:8000" r := newRouter() h := &http.Server{Addr: listenAt, Handler: r} go func() { log.Info("Serving on http://", listenAt) if err := h.ListenAndServe(); err != nil { log.Fatal(err) } }() <-stop log.Info("Stoping ...") h.Shutdown(context.Background()) log.Info("Bye :)")}示例處理程序func handler(w http.ResponseWriter, r *http.Request) { time.Sleep(5 * time.Second) log.Info("new request") fmt.Fprintf(w, "Hola!")}完整示例@ https://gist.github.com/nachopro/d80fa71ae49527e1ddcaf359b4ff488b
- 2 回答
- 0 關注
- 545 瀏覽
添加回答
舉報
0/150
提交
取消