相关疑难解决方法(0)

当请求具有正文(卷曲,邮递员)时,Go http 上下文无法捕获取消信号

可以使用以下简单的 go 代码片段重现该问题吗?

简单的 http 服务器:

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"
)

func handler(w http.ResponseWriter, r *http.Request) {
    go func(done <-chan struct{}) {
        <-done
        fmt.Println("message", "client connection has gone away, request got cancelled")
    }(r.Context().Done())

    time.Sleep(30 * time.Second)
    fmt.Fprintf(w, "Hi there, I love %s!\n", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}
Run Code Online (Sandbox Code Playgroud)

从 http 服务器上方开始,如果我GET使用 curl(邮递员也)发送一个简单的请求,例如:

curl -X GET http://localhost:8080/
Run Code Online (Sandbox Code Playgroud)

然后按Ctrl+C终止请求,然后我就可以在服务器端看到打印的消息:

message client connection has gone away, request got cancelled
Run Code Online (Sandbox Code Playgroud)

以上是我期望的正确行为:模拟当客户端离开时服务器可以捕获它然后尽早取消所有不必要的工作的情况。 …

curl http go postman

3
推荐指数
1
解决办法
766
查看次数

标签 统计

curl ×1

go ×1

http ×1

postman ×1