Skip to content

Instantly share code, notes, and snippets.

@ChyiYaqing
Created January 9, 2023 07:00
Show Gist options
  • Save ChyiYaqing/ab60600e5f523a06b30a1827d07c7ebe to your computer and use it in GitHub Desktop.
Save ChyiYaqing/ab60600e5f523a06b30a1827d07c7ebe to your computer and use it in GitHub Desktop.
golang context.DeadlineExceeded
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"time"
)
func slowServer(w http.ResponseWriter, r *http.Request) {
time.Sleep(10 * time.Second)
w.Write([]byte("Hello world!"))
}
func call() error {
client := &http.Client{Timeout: 1 * time.Second}
req, err := http.NewRequest(http.MethodGet, "http://localhost:9080", nil)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(req.Context(), 1*time.Second)
defer cancel()
req = req.WithContext(ctx)
_, err = client.Do(req)
return err
}
func main() {
// run slow server
go func() {
http.HandleFunc("/", slowServer)
if err := http.ListenAndServe(":9080", nil); err != nil {
log.Fatal(err)
}
}()
time.Sleep(1 * time.Second) // wait for server to run
// call server
err := call()
// An HTTP client returns the context.DeadlineExceeded error when the set timeout is exceeded.
if errors.Is(err, context.DeadlineExceeded) {
log.Println("ContextDeadlineExeeded: true")
}
if os.IsTimeout(err) {
log.Println("IsTimeoutError: true")
}
if err != nil {
log.Fatal(err)
}
}
@ChyiYaqing
Copy link
Author

Context Deadline Exceeded is an error occurring in Go when a context of an HTTP request has a deadline or a timeout set

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment