doudi1979 2019-07-29 03:24
浏览 127
已采纳

请求正文时,转到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.
  • 写回答

1条回答 默认 最新

  • doupai5450 2019-07-29 04:19
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c