12/03/2020 - GO
Aşağıda listelenen iki senaryoyu kullanarak tüm aktif sorguları context ile durduracağız.
WithTimeout
özelliğini kullanan alt context'in sorumluluğu olacaktır. Sorgu duracak ve context deadline exceeded
hatası verecek.WithCancel
özelliğini kullanan ana context'in sorumluluğu olacaktır. Sorgu duracak ve context canceled
hatası verecek.Yukarıda açıklandığı gibi, tüm uygulama için bir ana context ve ana içerikten türetilen bir alt içeriğe sahibiz. Sonuç olarak:
Ana context'i HTTP sunucusunun BaseContext
parametresi olarak ayarlıyoruz ve böylece istek kapsamı boyunca bizim için kullanılabilir hale gelecektir.
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
},
}
// ...
}
Ana context'i HTTP isteğinden aldığınızdan ve sorguyu çalıştırdığınız yere enjekte ettiğinizden emin olun. Şu anda ben her şeyi işleyicide yapıyorum.
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`)
// ...
}