We are going to halt all active queries with context by using two scenarios as listed below.



As described above, we have a parent context for the whole application and a child context derived from the parent context. As a result:



Example


We are setting our parent context as HTTP server's BaseContext so it is be available for us throughout the request scope.


func main() {
// Parent context.
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

srv := &http.Server{
Addr: "some-address",
Handler: "some-handler",
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
}

// ...
}

Make sure you grab the parent context from HTTP request and inject into where you run the query. Currently I am doing everything in the handler.


func myHandler(w http.ResponseWriter, r *http.Request) {
// Grab the parent context.
ctx := r.Context()

// Create child context derived from the parent context.
ctx, cancel := context.WithTimeout(ctx, 5 * time.Second)
defer cancel()

// Link the child context to the query.
rows, err := DB.QueryContext(ctx, `some query`)
// ...
}