golang捕获http.ResponseWriter被close的两种方式(有无context
golang捕获http.ResponseWriter被close的两种方式(有无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的通知一个简单的用法 func SomeHandler(resp http.ResonseWriter,req *http.Request) { notify := resp.(CloseNotifier).CloseNotify() go func() { <-notify lock.RLock() fmt.Println("HTTP connection just closed.") lock.RUnlock() }() } 当传入参数不确定是否是resp时 通知只有一次,需要向后继续传递这是golang关于context的介绍,https://godoc.org/golang.org/x/net/context ctx,cancel := context.WithCancel(context.Background()) 当获得通知后,执行了cancel方法,如果后续操作也依赖这个通知,这时需要获得另一个信号,ctx.Done() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |