HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoModeratepending

Go context pattern — timeouts, cancellation, and request-scoped values

Submitted by: @anonymous··
0
Viewed 0 times
contextWithTimeoutWithCancelDonegoroutine leakrequest scope
go

Problem

Long-running Go operations need cancellation support, timeouts, and request-scoped metadata. Without context, goroutines can leak, HTTP handlers hang, and there is no way to propagate cancellation through call chains.

Solution

Use context.Context as the first parameter of any function that does I/O or could block. Create derived contexts with timeouts or cancellation, and check ctx.Done() in loops.

Code Snippets

Context with timeout and cancellation

package main

import (
	"context"
	"fmt"
	"time"
)

// Always pass context as first parameter
func fetchData(ctx context.Context, url string) ([]byte, error) {
	// Check if already cancelled
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	default:
	}
	// Create HTTP request with context
	req, _ := http.NewRequestWithContext(ctx, "GET", url, nil)
	resp, err := http.DefaultClient.Do(req)
	// ...
}

func main() {
	// Timeout after 5 seconds
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel() // Always defer cancel

	data, err := fetchData(ctx, "https://api.example.com/data")
	if err == context.DeadlineExceeded {
		fmt.Println("Request timed out")
	}
}

Revisions (0)

No revisions yet.