This is a creation in Article, where the information may have evolved or changed.
Golang captures HTTP. Responsewriter two ways of being close (with or without context)
Easy to be circulated, the use of Chinese, in fact, used to look at English, found that Chinese for some problems, read up around the mouth, followed by a lot of direct copy of English, the following simple introduction:
- Why the server needs to know that the HTTP connection is disconnected (client active cancel)
- The simplest way to capture
- How to capture a message when the context is used to pass it
- How to continue delivery after context capture
Demand
Spit trough oneself, the first time with Csdn's new editor is very unfamiliar
Most Web Requests is 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.
This is very good, the client if it shuts down what to do, we can not sit idly by.
Catch notification of Cancel
A simple usage
Start with a 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()}()
}
When an incoming parameter is not determined whether it is RESP
First make a simple judgment, using reflect, assuming that RESP is what you think of 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
}
}
Notifications are only one time and need to be passed back
This is Golang's introduction to the context, Https://godoc.org/golang.org/x/net/context
CTX, Cancel: = context. Withcancel (context. Background ())
When notified, the Cancel method is executed, and if subsequent operations also rely on this notification, then another signal is needed, CTX. Done ()
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.