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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件