Go Language Http.get () timeout setting (update)

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

Last time I wrote the log share http. Get () sets the scheme for timeouts (the previous article), and later went through the code discovery logically problematic.

After Dail, the deadline is set, and then it is not reset. This is not a problem for HTTP requests that do not reuse connections, but the HTTP library for GO is keep-alive-capable and can be reused for TCP/IP connections. This means that a timeout error occurs after a connection has been made to the timeout period, because no longer resets the timeout.

Take the last experiment code, add a keep-alive header when sending the request, and then add a sleep before each request, you can re-the above situation.

How do I set a timeout before sending and receiving one connection at a time? I thought of a way to return the dial callback to the wrapped timeoutconn, indirectly invoke the real conn, so that you can set the time-out before each read and write.

The following is the modified experiment code:

How to set timeout for HTTP. Get () in Golang//package mainimport ("io" "io/ioutil" "Log" "Net" "Net/http" "Sync" "Time") type Time outconn struct {conn net. Conn timeout time. Duration}func NEWTIMEOUTCONN (Conn net. Conn, timeout time. Duration) *timeoutconn {return &timeoutconn{conn:conn, Timeout:timeout,}}func (c *TIMEOUTC Onn) Read (b []byte) (n int, err error) {C.setreaddeadline (time. Now (). ADD (c.timeout)) return C.conn.read (b)}func (c *timeoutconn) Write (b []byte) (n int, err error) {C.setwritedeadline ( Time. Now (). ADD (c.timeout)) return C.conn.write (b)}func (c *timeoutconn) Close () error {return c.conn.close ()}func (c *TIMEOUTC Onn) localaddr () net. Addr {return c.conn.localaddr ()}func (c *timeoutconn) remoteaddr () net. Addr {return c.conn.remoteaddr ()}func (c *timeoutconn) Setdeadline (t time. Time) Error {return C.conn.setdeadline (t)}func (c *timeoutconn) Setreaddeadline (t time. Time) Error {RETUrn C.conn.setreaddeadline (t)}func (c *timeoutconn) Setwritedeadline (t time. Time) Error {return C.conn.setwritedeadline (t)}func Main () {client: = &http. client{Transport: &http. transport{Dial:func (netw, addr string) (net. Conn, error) {log. Printf ("dial to%s://%s", NETW, addr) conn, err: = Net. Dialtimeout (NETW, addr, time. SECOND*2) If err! = Nil {return nil, err} return NewTime OUTCONN (conn, time. second*2), nil}, Responseheadertimeout:time. Second * 2,},} addr: = Starttestserver () sendtestrequest (client, "1st", addr, "normal") Sendtestreque St (Client, "2st", addr, "normal") sendtestrequest (client, "3st", addr, "timeout") sendtestrequest (client, "4st", add R, "normal") time. Sleep (time. Second * 3) sendtestrequest (client, "5st", addr, "normal")}func Starttestserver () string {listener, err: = Net. Listen ("TCP", ": 0") if err! = Nil {log. Fatalf ("Failed to listen-%s", Err. Error ())} WG: = new (sync. WAITGROUP) WG. ADD (1) go func () {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")}) WG. Done () Err = http. Serve (listener, nil) if err! = Nil {log. Fatalf ("Failed to start HTTP server-%s", Err. Error ())}} () WG. Wait () log. Printf ("Start HTTP Server at http://%s/", listener. ADDR ()) return listener. Addr (). String ()}func sendtestrequest (client *http. Client, id, addr, path string) {req, err: = http. Newrequest ("GET", "http://" +addr+ "/" +path, nil) if err! = Nil {log. Fatalf ("New request failed-%s", err)} req. HeaDer. ADD ("Connection", "keep-alive") switch path {case "normal": If resp, err: = client. Do (req); Err! = Nil {log. Fatalf ("%s request failed-%s", ID, err)} else {result, err2: = Ioutil. ReadAll (resp. Body) if err2! = Nil {log. Fatalf ("%s response read failed-%s", ID, ERR2)} resp. Body.close () log. Printf ("%s request-%s", ID, result)} case "Timeout": If _, Err: = client. Do (req); Err = = Nil {log. Fatalf ("%s Request not timeout", id)} else {log. Printf ("%s request-%s", ID, err)}}
Related Article

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.