Skip to content

Commit

Permalink
Improved req package
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Jul 21, 2016
1 parent 68db635 commit 221c984
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
5 changes: 5 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
36 changes: 33 additions & 3 deletions req/req.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
)

// ////////////////////////////////////////////////////////////////////////////////// //
Expand Down Expand Up @@ -149,6 +155,8 @@ func (r Request) Do() (*Response, error) {
req.Close = true
}

initTransport()

resp, err := Client.Do(req)

if err != nil {
Expand Down Expand Up @@ -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:
Expand Down

0 comments on commit 221c984

Please sign in to comment.