golang捕獲http.ResponseWriter被close的兩種方式(有無context)

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

golang捕獲http.ResponseWriter被close的兩種方式(有無context)

方便被傳閱,採用中文,其實習慣看英文後,發現中文對於一些問題,讀起來繞口,接下來有很多也是直接照搬英文,以下幾個方面簡單介紹下:
- 為嘛服務端需要知道http串連被斷開(用戶端主動cancel)
- 最簡單的方式捕獲
- 當使用了context來傳遞資訊時,如何捕獲
- context捕獲後,如何繼續傳遞

需求

吐槽下自己 ,第一次用CSDN的新款編輯器很是生疏

Most web requests by design take only a few dozen milliseconds to process. But sometimes web apps need to leave a connection open for a longer period of time. And sometimes the remote client closes the connection before the server has had time to respond.

On a Go-based webserver, you can receive notifications when the HTTP connection terminates.
這講的就很好,用戶端它要是關了怎麼辦,咱們不能坐以待斃啊。

捕獲cancel的通知

一個簡單的用法
Start with an HTTP handler function, and get the channel for close notifications:

func SomeHandler(resp http.ResonseWriter, req *http.Request) {
// Normal stuff
//…

notify := resp.(CloseNotifier).CloseNotify()go func() {    <-notify    lock.RLock()    fmt.Println("HTTP connection just closed.")    lock.RUnlock()}()

}

當傳入參數不確定是否是resp時
先做個簡單的判斷,採用reflect,假設resp 是你認為的http.ResponseWriter
v := reflect.ValueOf(resp)
v = reflect.Indirect(v)
for v.Kind() == reflect.Struct {
if fv := v.FieldByName(“ResponseWriter”); fv.IsValid() {
if cn, ok = fv.Interface().(http.CloseNotifier); ok {
return
}
v = reflect.Indirect(fv)
} else {
break
}
}

通知只有一次,需要向後繼續傳遞

這是golang關於context的介紹,https://godoc.org/golang.org/x/net/context

ctx, cancel := context.WithCancel(context.Background())
當獲得通知後,執行了cancel方法,如果後續操作也依賴這個通知,這時需要獲得另一個訊號,ctx.Done()

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.