Cancel and Context Net/http provides two methods for revoking client requests: Request.cancel and the context provided in the new version 1.7. The Request.cancel is an optional channel. When the request.timeout is triggered, the request.cancel will be set and closed, causing the request to be interrupted (basically "undo" is the same mechanism, when writing this article, I found a 1.7 bug, all undo operation, will be as a timeout error returned). We can use Request.cancel and time.timer to build a time-out more controllable client that can be used for streaming media. It can reset the deadline after successful response to some of the data in the genre (Body). package mainimport ( "io" "Io/ioutil" "Log" "Net/http" "Time") Func main () { c := make (chan struct{}) Timer := time. Afterfunc (5*time. Second, func () { close (c) }) // serve 256 bytes every second. req, err := http. Newrequest ("GET", "http://httpbin.org/range/2048?duration=8&chunk_size=256", nil) if err != nil { log. Fatal (Err) } req. Cancel = c log. Println ("Sending request ...") resp, err := http. Defaultclient.do (req) if err != nil { log. Fatal (Err) } defer resp. Body.close () log. Println ("Reading body ...") for { timer. Reset (2 * time. Second) // try instead: timer. Reset (50 * time.millisecond) _, err = io. Copyn (Ioutil. Discard, resp. body, 256) if err == io. eof { break } else if err != nil { &Nbsp; log. Fatal (Err) } }} In the above example, we set a 5-second timeout in the request phase. But read the response message phase, we need to read 8 times, at least 8 seconds. For each read operation, set a timeout of 2 seconds. With this mechanism, we can gain unrestricted access to streaming media without worrying about the risk of blocking. If we do not read any data within 2 seconds, Io. Copyn will return an error message: Net/http:request canceled. A new context package has been added to the 1.7 version of the standard library. About contexts, we have a lot of things to learn. Based on the gist of this article, the first thing you should know is that contexts will replace request.cancel and no longer suggest (oppose) using Request.cancel. |
Caotj72 Translated 6 days ago 0 Person Top top translation of good Oh! |