這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
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()
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。