Go Language Http.get () timeout setting

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The scheme in this article is flawed, this article is only as a historical record, the complete program please refer to (this) [HTTP://1234N.COM/?POST/MWSW2R]

A complete HTTP client and server functionality is provided in the go-to-HTTP package. Recent projects have several requirements that require an HTTP request from the game server to invoke the interface provided by the operator. The go language is super simple, http. Get () tune it out.

However, HTTP. Get () is a timeout that does not provide parameters for the caller to set the connection and read-write, and the item is encountered on-line permanently blocked in HTTP. Get () does not return the condition.

The internet to find a bit of information, and finally solve the problem, the following is the test code, first paste code re-analysis principle (gist connection):

How to set timeout for HTTP. Get () in Golang//package mainimport ("io" "io/ioutil" "Log" "Net" "Net/http" "Time") Func Starttestserve R () string {http. Handlefunc ("/normal", func (w http). Responsewriter, req *http. Request) {time. Sleep (time.millisecond) io. WriteString (W, "OK")}) http. Handlefunc ("/timeout", func (w http). Responsewriter, req *http. Request) {time. Sleep (2500 * time.millisecond) io. WriteString (W, "OK")}) Listener, err: = Net. Listen ("TCP", ": 0") if err! = Nil {log. Fatalf ("Failed to listen-%s", Err. Error ())} go func () {err = http. Serve (listener, nil) if err! = Nil {log. Fatalf ("Failed to start HTTP server-%s", Err. Error ())}} () log. Printf ("Start HTTP Server at http://%s/", listener. ADDR ()) return listener. Addr (). String ()}func main () {addr: = Starttestserver () client: = &http. client{Transport: &http.            transport{Dial:func (NETW, addr string) (net. Conn, error) {Conn, err: = Net. Dialtimeout (NETW, addr, time. SECOND*2) If err! = Nil {return nil, err} conn. Setdeadline (time. Now (). ADD (time. Second * 2)) return conn, nil}, Responseheadertimeout:time. Second * 2,},}//1st request if RESP, err: = client. Get ("http://" + addr + "/normal"); Err! = Nil {log. Fatalf ("1st request failed-%s", err)} else {result, err2: = Ioutil. ReadAll (resp. Body) if err2! = Nil {log. Fatalf ("1st response read failed-%s", ERR2)} resp. Body.close () log. Printf ("1st Request-%s", result)}//2nd Request If _, err: = client. Get ("http://" + addr + "/timeout"); Err = = Nil {log. Fatalf ("2nd not timeout")} else {log. Printf ("2nd request-%s", err)}//3rd request if RESP, err: = client. Get ("http//" + Addr + "/normal"); Err! = Nil {log. Fatalf ("3rd request-%s", err)} else {result, err2: = Ioutil. ReadAll (resp. Body) if err2! = Nil {log. Fatalf ("3rd response read failed-%s", ERR2)} resp. Body.close () log. Printf ("3rd request-%s", result)}}

The most important thing in the code is to create HTTP. The section of the client where HTTP is customized. Client's transport, while transport creates a dial-up callback that, in the dial-up callback, uses Dialtimeout to support the connection timeout, and when the connection succeeds, the setdeadline is used to enable the connection to read and write timeouts.

HTTP packets are provided by HTTPS. Get actually invokes a pre-created defaultclient, and defaultclient uses the default transport, which is easy to see from the code of the HTTP package.

The default client and transport do not have timeout settings, so we need to create http ourselves. Client to implement an HTTP client with a timeout feature.

The HTTP packet also has an easy pit-to-novice pit point, which is the HTTP returned after the request. Response, you must call Body.close (), the document is written, but it is easy to ignore, and the Close method is not on the Response type, but on the Body property.

If Body.close () is not called, the TCP connection used by the HTTP request will not be freed, and the number of connections will eventually appear too large.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.