Getting started with the Go language HTTP request Timeout

Source: Internet
Author: User
Tags cloudflare
In distributed systems, timeouts are one of the basic reliability concepts. As mentioned in this [tweet] (https://twitter.com/copyconstruct/status/1025241837034860544), it can mitigate the impact of an unavoidable failure in a distributed system. # # Question > How to conditionally Simulate 504 HTTP. Statusgatewaytimeout Response. When trying to implement OAuth token validation in [Zalando/skipper] (https://github.com/zalando/skipper/issues/633), I had to understand and try to use Httptest Implement a test to [impersonate a] when the server is timed out (https://stackoverflow.com/questions/51319726/ HOW-TO-MIMIC-504-TIMEOUT-ERROR-FOR-HTTP-REQUEST-INSIDE-A-TEST-IN-GO) [504 http. Statusgatewaytimeout] (https://stackoverflow.com/questions/51319726/ How-to-mimic-504-timeout-error-for-http-request-inside-a-test-in-go). But because of the server delay, only the client's timeout is generated. As a beginner of this language, like most people, I created a standard HTTP Client with timeouts. "' Goclient: = http. Client{timeout:5 * time. Second} "When you want to create a client to send an HTTP request, the code above looks very simple and intuitive. But underneath it hides a lot of low-level details, including client timeouts, server timeouts, and load-balancing timeouts. # # The HTTP request timeout for the client timeout client has several forms, depending on the location of the timeout frame throughout the request process. The entire request response process is composed of ' Dialer ', ' TLS handshake ', ' request header ', ' request body ', ' Response header ' and ' Response body '. Depending on the different parts of the request response process, Go provides the following ways to create a request with a timeout. * ' http.client ' * 'Context ' * ' http. Transport ' # # http.client: ' http.client ' timeout is a high-level implementation of timeouts, containing the entire request flow from ' Dial ' to ' Response Body '. The implementation of ' http.client ' provides a struct type that can accept an additional ' time '. The ' Timeout ' property of Duration ' type. This parameter defines the time limit from the start of the request to the full receipt of the response message body. "' Goclient: = http. Client{timeout:5 * time. The ' context ' package of the Second} ' # # Contextgo language provides some useful tools to handle timeouts by using ' withtimeout ', ' withdeadline ' and ' Withcancel ' methods, Deadline And a request that can be canceled. With ' Withtimeout ', you can go through ' req. Withcontext ' method to ' HTTP '. Request ' added a time-out. "' Goctx, Cancel: = context. Withtimeout (context. Background (), 50*time.millisecond) defer cancel () req, err: = http. Newrequest ("GET", url, nil) if err! = Nil {t.error ("Request Error", err)}resp, err: = http. Defaultclient.do (req. Withcontext (CTX)) ' # # HTTP. Transport: You can also use custom ' http with ' Dialcontext '. Transport ' to create a low-level implementation of ' http.client ' to specify the time-out. "' Gotransport: = &http. transport{Dialcontext: (&net. dialer{Timeout:timeout,}). Dialcontext,}client: = http. Client{transport:transport} ' # # Solution according to the above questions and various options I passed ' context. Withtimeout () ' created a ' http.requeSt '. But it still fails and gets the following error. ' Client_test.go:40:response error Get Http://127.0.0.1:49597:context deadline exceeded ' # # Server timeout using ' context. The problem with withtimeout () ' Is that it is still just impersonating the requesting client. In the event that the requested header or message body exceeds the predefined timeout period, the request will fail directly on the client without returning ' 504 HTTP ' from the server. Statusgatewaytimeout ' status code. Create a Httptest service code that is timed out each time: ' ' gohttptest. NewServer (http. Handlerfunc (Func (w http. Responsewriter, _ *http. Request) {W.writeheader (http. statusgatewaytimeout)}) "But I just want the server to time out based on the value set by the client. In order for the server to return 504 status codes based on the client timeout, you can use ' http '. The Timeouthandler () ' function wraps the handler to make the request fail on the service side. The following is a running test code that conforms to the requirements of the scene. "' Gofunc testclienttimeout (t *testing. T) {handlerfunc: = http. Handlerfunc (Func (w http. Responsewriter, R *http. Request) {d: = map[string]interface{}{"id": "A", "Scope": "Test-scope",} time. Sleep (Time.millisecond)//<-any value > 20ms B, err:= json. Marshal (d) if err! = Nil {t.error (err)} io. WriteString (W, string (b)) W.writeheader (http. Statusok)}) Backend: = Httptest. NewServer (http. Timeouthandler (Handlerfunc, 20*time.millisecond, "Server timeout") URL : = backend. URL req, Err: = http. Newrequest ("GET", url, nil) if err! = Nil {t.error ("Request Error", err) return} resp, err: = http. Defaultclient.do (req) If err! = Nil {t.error ("Response Error", err) return} Defer resp. Body.close ()} "" In the Project [Zalando/skipper] (https://github.com/zalando/skipper/) [Oauth_test/testoauth2tokentimeout] ( HTTPS://GITHUB.COM/ZALANDO/SKIPPER/BLOB/MASTER/FILTERS/AUTH/OAUTH_TEST.GO#L378:6) contains specific information about the above issues in the implementation. It may be useful for beginners of the Go language to understand the high level of HTTP timeouts. But if you want to know more about the ' HTTP timeouts ' details in Go, this [Cloudflare] (https://blog.cloudflare.com/ the-complete-guide-to-golang-net-http-timeouts/) on the article is worth reading.

via:https://medium.com/@addityasingh/HTTP-REQUEST-TIMEOUTS-IN-GO-FOR-BEGINNERS-FE6445137C90

Author: Aditya Pratap Singh Translator: Alfred-zhong Proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

185 Reads
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.