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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

The `context` Package – Can | Go Programming Bootcamp lesson | BraveProgrammer
  1. Courses
  2. /
  3. Go Programming Bootcamp

Lesson 17 of 60

·Go

The `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))
}
error
nil
if
nil
return
nil
defer
return
func main()
2
defer
"https://example.com"
if
nil
string

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)).
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from Go Programming BootcampBrowse activities
Previous lessonAtomic Operations & MutexesContinue to lesson 18Standard Library: `net/http` – Building a Simple Web ServerBack to Go Programming Bootcamp curriculum