Lesson 17 of 60
GoThe `context` Package – Cancellation & Timeouts
20 minutes
Course progress28%
Context
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
context.Context carries deadlines, cancellation signals, and request‑scoped values.
func fetch(ctx context.Context, url string) ([]byte, ) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, )
resp, err := http.DefaultClient.Do(req)
err != { , err }
resp.Body.Close()
io.ReadAll(resp.Body)
}
{
ctx, cancel := context.WithTimeout(context.Background(), *time.Second)
cancel()
data, err := fetch(ctx, )
err != { log.Fatal(err) }
fmt.Println((data))
}