Created
March 21, 2019 15:01
-
-
Save klingtnet/ac77450a03d4ebd0342edde5ae12d6f6 to your computer and use it in GitHub Desktop.
Handle HTTP client timeout in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io/ioutil" | |
"log" | |
"net/http" | |
"net/http/httptest" | |
"net/url" | |
"time" | |
) | |
func main() { | |
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
time.Sleep(10 * time.Second) | |
w.Write([]byte("Did you sleep well?")) | |
})) | |
cl := &http.Client{ | |
Timeout: 1 * time.Second, | |
} | |
req, err := http.NewRequest("GET", srv.URL, nil) | |
if err != nil { | |
log.Fatal("request creation failed: ", err) | |
} | |
resp, err := cl.Do(req) | |
if err != nil { | |
if urlErr, ok := err.(*url.Error); ok { | |
if urlErr.Timeout() { | |
log.Fatalf("request timed-out: %+v", urlErr) | |
} | |
} | |
log.Fatal("request failed: ", err) | |
} | |
defer resp.Body.Close() | |
data, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatal("failed to read response body: ", err) | |
} | |
log.Println(string(data)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment