Skip to content

Commit

Permalink
Merge pull request #102 from pierrre/feature/client-timeout
Browse files Browse the repository at this point in the history
add Client HTTP timeout
  • Loading branch information
michaelklishin authored Jul 9, 2017
2 parents 69babda + a21f5a6 commit cbe44ff
Showing 1 changed file with 14 additions and 18 deletions.
32 changes: 14 additions & 18 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"net/url"
"time"
)

type Client struct {
Expand All @@ -17,6 +18,7 @@ type Client struct {
Password string
host string
transport *http.Transport
timeout time.Duration
}

func NewClient(uri string, username string, password string) (me *Client, err error) {
Expand Down Expand Up @@ -58,6 +60,12 @@ func (c *Client) SetTransport(transport *http.Transport) {
c.transport = transport
}

// SetTimeout changes the HTTP timeout that the Client will use.
// By default there is no timeout.
func (c *Client) SetTimeout(timeout time.Duration) {
c.timeout = timeout
}

func newGETRequest(client *Client, path string) (*http.Request, error) {
s := client.Endpoint + "/api/" + path
req, err := http.NewRequest("GET", s, nil)
Expand Down Expand Up @@ -97,29 +105,17 @@ func newRequestWithBody(client *Client, method string, path string, body []byte)
}

func executeRequest(client *Client, req *http.Request) (res *http.Response, err error) {
var httpc *http.Client
if client.transport != nil {
httpc = &http.Client{Transport: client.transport}
} else {
httpc = &http.Client{}
httpc := &http.Client{
Timeout: client.timeout,
}
res, err = httpc.Do(req)

if err != nil {
return nil, err
if client.transport != nil {
httpc.Transport = client.transport
}

return res, nil
return httpc.Do(req)
}

func executeAndParseRequest(client *Client, req *http.Request, rec interface{}) (err error) {
var httpc *http.Client
if client.transport != nil {
httpc = &http.Client{Transport: client.transport}
} else {
httpc = &http.Client{}
}
res, err := httpc.Do(req)
res, err := executeRequest(client, req)
if err != nil {
return err
}
Expand Down

0 comments on commit cbe44ff

Please sign in to comment.