浏览文件
lifecycle_http.go
28 行 · 771 B历史下载| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net/http" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | // Cancelling a context alone cannot release a slow request-body read or a |
| 10 | // response write. HTTP deadlines interrupt both without closing a reused |
| 11 | // connection after its handler has returned. A genuine upgrade also owns its |
| 12 | // WebSocket cancellation; an Upgrade header alone must not bypass body cleanup. |
| 13 | func interruptHTTPOnCancel(w http.ResponseWriter, r *http.Request) func() { |
| 14 | done := make(chan struct{}) |
| 15 | body := r.Body |
| 16 | stop := context.AfterFunc(r.Context(), func() { |
| 17 | defer close(done) |
| 18 | controller := http.NewResponseController(w) |
| 19 | _ = controller.SetReadDeadline(time.Now()) |
| 20 | _ = controller.SetWriteDeadline(time.Now()) |
| 21 | _ = body.Close() |
| 22 | }) |
| 23 | return func() { |
| 24 | if !stop() { |
| 25 | <-done |
| 26 | } |
| 27 | } |
| 28 | } |

