Skip to main content
InterviewHubPRO
Section Overview
Q15

Question 15 of 50

Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

30%
Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

The `context` Package: `WithCancel`, `WithTimeout`, and Cancellation Propagation.

senior LevelCode ExamplegolangGo Language Core

In Simple Words: The context.Context interface carries cancellation signals, deadlines, and request-scoped values across API boundaries and goroutines.

When an HTTP client disconnects or a timeout expires, ctx.Done() closes its channel. All child goroutines listening to ctx.Done() terminate immediately, preventing orphaned background database queries and resource waste.

go
func queryDatabase(ctx context.Context) error {
	req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.internal/data", nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err // Automatically aborted if context timed out or was cancelled
	}
	defer resp.Body.Close()
	return nil
}