This question already has an answer here:
- Specifically check for timeout error 3 answers
I am trying to make a HTTP call to a server and am using a 10 second client timeout. The current (incorrect) way of how I am handling it is like this:
package checks
import "net/http"
import "fmt"
import "log"
import "time"
import "strings"
var client = &http.Client{Timeout: 10 * time.Second}
func HttpCheck(url string) (string, error) {
log.Printf("initiating http get to %s
", url)
resp, err := client.Get(url)
if err != nil {
if strings.Contains(err.Error(), "Client.Timeout") {
return "loading", nil
} else {
log.Printf("error while getting url : %s
", err.Error())
return "", err
}
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Printf("got a non 200 response: %d", resp.StatusCode)
return "", fmt.Errorf("Server returned non 200 status: %d", resp.StatusCode)
}
log.Println("all is well, returning a success")
return "up", nil
}
The actual error thrown by Go httpError
is unexported.
How do I reliably handle a client timeout?
</div>