golang捕获http.ResponseWriter被close的两种方式(有无context)
2015-08-04 00:48
1246 查看
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/contextctx, cancel := context.WithCancel(context.Background())
当获得通知后,执行了cancel方法,如果后续操作也依赖这个通知,这时需要获得另一个信号,ctx.Done()
相关文章推荐
- Go语言将支持Android
- Golang实现的聊天程序服务端和客户端代码分享
- Golang学习笔记(三):控制流
- Golang学习笔记(二):类型、变量、常量
- Golang中的sync.WaitGroup用法实例
- Go语言struct类型介绍
- golang使用正则表达式解析网页
- Golang极简入门教程(三):并发支持
- Golang极简入门教程(四):编写第一个项目
- Golang记录、计算函数执行耗时、运行时间的一个简单方法
- Golang学习笔记(四):array、slice、map
- 理解Golang中的数组(array)、切片(slice)和map
- golang语言中for循环语句用法实例
- Golang学习笔记(一):简介
- golang操作mongodb的方法
- GO语言(golang)基础知识
- ubuntu下搭建Go语言(golang)环境
- Golang 内存模型详解(一)
- 在Golang中使用C语言代码实例
- Golang极简入门教程(二):方法和接口