How to Implement Request-Scoped Goroutine Lifetimes

Manually manage goroutine lifetimes in Go by passing a context.Context to the goroutine and calling cancel() when the request completes.

Go does not natively support request-scoped goroutine lifetimes; you must manually manage cancellation using context.Context. Pass a context derived from the request handler to your goroutine and cancel it when the request finishes.

func handler(w http.ResponseWriter, r *http.Request) {
    ctx, cancel := context.WithCancel(r.Context())
    defer cancel()

    go func() {
        select {
        case <-ctx.Done():
            return
        case result := <-doWork(ctx):
            // Handle result
        }
    }()

    // Wait for request to complete or timeout
    w.WriteHeader(http.StatusOK)
}