请求正文时,转到http上下文无法捕获取消信号(curl,postman)

The problem can be reproduced with the below simple go code snippet:

Simple go http server:

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!
", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Start above http server, if i send one simple GET request with curl(postman also) like:

curl -X GET http://localhost:8080/

then press Ctrl+C to terminate the request, then i am able to see the printed message at server side:

message client connection has gone away, request got cancelled

above is the correct behaviour i expect: to simulate the situation that when client is gone the server can capture it and then cancel all the unnecessary work as early as it can.

But when i send one POST request with request body, this expected behaviour doesn't happen, the <-done signal was captured until the request deadline meet.

curl -X POST http://localhost:8080/ -H 'Content-Type: application/json' -d '{}'

To summarize my questions:

  1. Why and how the curl(postman) GET, POST (with or without request body) request make such a difference?
  2. How should i handle this case properly with go context package, i mean to capture the client is gone signal as soon as it can, and so further to cancel the server side unnecessary work to release the resources as early as it can.
duanjiu1950
duanjiu1950 感谢您的答复,我了解到,以上代码仅用于重现我遇到的问题:我无法在POST请求的情况下捕获取消信号。
大约一年之前 回复
dqqxkq4047
dqqxkq4047 重新上下文。将r.Context()传递给任何子任务,例如SQL查询;http/gRPC调用等-并且将按设计链接上下文取消。子任务将因此导致取消错误。如果您想以自己的代码轮询请求上下文,例如等待循环,然后在上下文通道上使用select以及您的等待计时器通道。
大约一年之前 回复

1个回答

Read the request body to detect when the client closes the connection:

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())

    io.Copy(ioutil.Discard, r.Body) // <-- read the body
    time.Sleep(30 * time.Second)
    fmt.Fprintf(w, "Hi there, I love %s!
", r.URL.Path[1:])
}

The net/http server checks for closed connections by reading the connection. No reads are started until the application starts reading the request body (if any).

dou31797719
dou31797719 我不知道任何文档。 该行为源自以下事实:读取或写入是检测Go中关闭的连接的唯一方法。
大约一年之前 回复
duandi6531
duandi6531 啊,ic,很棒的ðŸ'ðŸ'ðŸ',我花了两个三个小时来尝试理解这种行为!
大约一年之前 回复
douwendu2460
douwendu2460 我试图在go doc上找到关于此的任何注释,但是我什么也没找到,但是它确实解决了OP的问题。 您是否有与此相关的链接或文档?
大约一年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐