From 221c984afc98c82918cf4faaed1f9023cd12de3c Mon Sep 17 00:00:00 2001 From: Anton Novojilov Date: Thu, 21 Jul 2016 19:15:08 -0400 Subject: [PATCH] Improved req package --- changelog.md | 5 +++++ req/req.go | 36 +++++++++++++++++++++++++++++++++--- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/changelog.md b/changelog.md index 75d2f416..e168e868 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,10 @@ ## Changelog +#### v3.1.0 + +* `[req]` Lazy transport initialization +* `[req]` Added `DialTimeout` and `RequestTimeout` variables for timeouts control + #### v3.0.3 * `[system]` Removed debug output diff --git a/req/req.go b/req/req.go index b307f11b..4ce38aae 100644 --- a/req/req.go +++ b/req/req.go @@ -82,14 +82,20 @@ var ( // UserAgent is default user-agent used for all requests UserAgent = "" + // DialTimeout is dial timeout in seconds + DialTimeout = 10.0 + + // RequestTimeout is request timeout in seconds + RequestTimeout = 5.0 + // Dialer default dialer struct - Dialer = &net.Dialer{Timeout: 10 * time.Second} + Dialer *net.Dialer // Transport is default transport struct - Transport = &http.Transport{Dial: Dialer.Dial, Proxy: http.ProxyFromEnvironment} + Transport *http.Transport // Client default client struct - Client = &http.Client{Transport: Transport} + Client *http.Client ) // ////////////////////////////////////////////////////////////////////////////////// // @@ -149,6 +155,8 @@ func (r Request) Do() (*Response, error) { req.Close = true } + initTransport() + resp, err := Client.Do(req) if err != nil { @@ -230,6 +238,28 @@ func (e RequestError) Error() string { // ////////////////////////////////////////////////////////////////////////////////// // +func initTransport() { + if Dialer == nil { + Dialer = &net.Dialer{ + Timeout: time.Duration(DialTimeout * float64(time.Second)), + } + } + + if Transport == nil { + Transport = &http.Transport{ + Dial: Dialer.Dial, + Proxy: http.ProxyFromEnvironment, + } + } + + if Client == nil { + Client = &http.Client{ + Transport: Transport, + Timeout: time.Duration(RequestTimeout * float64(time.Second)), + } + } +} + func getBodyReader(body interface{}) (io.Reader, error) { switch body.(type) { case nil: