Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 17 of 60 · Go

The `context` Package – Cancellation & Timeouts

Duration: 20 minutes

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, error) {
    req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    resp, err := http.DefaultClient.Do(req)
    if err != nil { return nil, err }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
    data, err := fetch(ctx, "https://example.com")
    if err != nil { log.Fatal(err) }
    fmt.Println(string(data))
}

Passing values via context

type key int
const requestIDKey key = 0

ctx = context.WithValue(ctx, requestIDKey, "abc-123")
id := ctx.Value(requestIDKey).(string)

Best practices

  • Never store large data structures in a Context.
  • Use context for cancellation and deadlines, not for passing optional parameters.

Info

When spawning goroutines, always derive a child context (ctx, cancel := context.WithCancel(parent)).

Previous: Atomic Operations & MutexesNext: Standard Library: `net/http` – Building a Simple Web Server