Skip to content

Commit

Permalink
fix(http): Improve timeout handling
Browse files Browse the repository at this point in the history
  • Loading branch information
elldritch committed Feb 23, 2018
1 parent d577588 commit da90056
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
21 changes: 18 additions & 3 deletions cmd/fossa/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,28 @@ import (
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"time"

logging "github.com/op/go-logging"
)

var commonLogger = logging.MustGetLogger("common")
var client = http.Client{
Timeout: 10 * time.Second,
}

func isTimeout(err error) bool {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
return true
}
if urlErr, ok := err.(*url.Error); ok && urlErr.Err == io.EOF {
return true
}
return false
}

// Common utilities among commands
func makeAPIRequest(method, endpoint, apiKey string, payload []byte) ([]byte, error) {
Expand All @@ -24,11 +39,11 @@ func makeAPIRequest(method, endpoint, apiKey string, payload []byte) ([]byte, er
req.Header.Set("Authorization", "token "+apiKey)
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
resp, err := client.Do(req)
if err != nil {
if err.(*url.Error).Err == io.EOF {
if isTimeout(err) {
commonLogger.Debugf("API request timed out")
return nil, err.(*url.Error).Err
return nil, err
}
return nil, fmt.Errorf("failed to send API HTTP request: %s", err.Error())
}
Expand Down
5 changes: 2 additions & 3 deletions cmd/fossa/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -46,7 +45,7 @@ func getBuild(endpoint, apiKey, project, revision string) (buildResponse, error)

testLogger.Debugf("Making Builds API request to: %#v", url)
res, err := makeAPIRequest(http.MethodPut, url, apiKey, nil)
if err == io.EOF {
if isTimeout(err) {
return buildResponse{}, err
}
if err != nil {
Expand Down Expand Up @@ -108,7 +107,7 @@ func doTest(s *spinner.Spinner, race chan testResult, endpoint, apiKey, project,
buildLoop:
for {
build, err := getBuild(endpoint, apiKey, project, revision)
if err == io.EOF {
if isTimeout(err) {
time.Sleep(pollRequestDelay)
continue
}
Expand Down

0 comments on commit da90056

Please sign in to comment.