http.TimeoutHandler 返回但 handlerfunc 继续运行

我正在我的http.timeoutHandlerGo Web 服务器中测试,我注意到 3 秒后我的客户端调用收到“ Timeout”消息,但 2 秒后我可以在服务器上看到消息“我的func Println”。为什么TimeoutHandler没有取消我的func1?


这是我正在使用的代码:


package main


import (

        "fmt"

        "io"

        "net/http"

        "time"

)


func func1(w http.ResponseWriter, req *http.Request) {

        time.Sleep(5 * time.Second)

        fmt.Println("My func Println")

        io.WriteString(w, "My func!\n")

}


func main() {

        srv := http.Server{

                Addr:         ":9000",

                WriteTimeout: 5 * time.Second,

                Handler:      http.TimeoutHandler(http.HandlerFunc(func1), 3*time.Second, "Timeout!\n"),

        }


        if err := srv.ListenAndServe(); err != nil {

                fmt.Printf("Server failed: %s\n", err)

        }

}


慕容森
浏览 197回答 1
1回答

慕无忌1623718

是的,这就是它的工作方式。当超时发生并且您的处理函数仍在运行(尚未返回)时,请求的上下文将被取消。您的处理程序负责监控 Context 的 Done 通道,并在请求取消时中止其工作。每个处理程序都在自己的 goroutine 中运行,并且 goroutine 不能被“外部”杀死或中断。示例如何做到这一点:func func1(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; select {&nbsp; &nbsp; case <-time.After(5 * time.Second):&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("My func Println")&nbsp; &nbsp; &nbsp; &nbsp; io.WriteString(w, "My func!\n")&nbsp; &nbsp; case <-req.Context().Done():&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("Cancelled")&nbsp; &nbsp; }}这将输出:Cancelled如果您将处理程序中的延迟更改为 2 秒:case <-time.After(2 * time.Second):输出将是:My func Println客户端接收发送的数据:My func!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go