From 5d8d89d24640107bac8f9597f177377821525898 Mon Sep 17 00:00:00 2001 From: Eli Bendersky Date: Sat, 4 Jan 2020 14:05:02 -0800 Subject: [PATCH] Provide some more background on Context And add a comment about the `Err()` method. Followup on #301 --- examples/context/context.go | 7 ++++++- examples/context/context.hash | 4 ++-- public/context | 24 ++++++++++++++++++++---- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/examples/context/context.go b/examples/context/context.go index 0ad734c..3971e19 100644 --- a/examples/context/context.go +++ b/examples/context/context.go @@ -1,7 +1,9 @@ // In the previous example we looked at setting up a simple // [HTTP server](http-servers). HTTP servers are useful for // demonstrating the usage of `context.Context` for -// controlling cancellation. +// controlling cancellation. A `Context` carries deadlines, +// cancellation signals, and other request-scoped values +// across API boundaries and goroutines. package main import ( @@ -28,6 +30,9 @@ func hello(w http.ResponseWriter, req *http.Request) { case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): + // The context's `Err()` method returns an error + // that explains why the `Done()` channel was + // closed. err := ctx.Err() fmt.Println("server:", err) internalError := http.StatusInternalServerError diff --git a/examples/context/context.hash b/examples/context/context.hash index 7cdacf5..5f6b83c 100644 --- a/examples/context/context.hash +++ b/examples/context/context.hash @@ -1,2 +1,2 @@ -5893bc5d4537db64f263a6be8efa9f2cda8ca7d8 -Elok_mfA6GV +e338acce5d0f64d6478be4b886bd24a0fd1a3afa +Lun5aFco3pX diff --git a/public/context b/public/context index a7bc320..f182bbe 100644 --- a/public/context +++ b/public/context @@ -30,11 +30,13 @@

In the previous example we looked at setting up a simple HTTP server. HTTP servers are useful for demonstrating the usage of context.Context for -controlling cancellation.

+controlling cancellation. A Context carries deadlines, +cancellation signals, and other request-scoped values +across API boundaries and goroutines.

- +
package main
 
@@ -101,7 +103,21 @@ the work and return as soon as possible.

case <-time.After(10 * time.Second): fmt.Fprintf(w, "hello\n") case <-ctx.Done(): - err := ctx.Err() + + + + + + + +

The context’s Err() method returns an error +that explains why the Done() channel was +closed.

+ + + + +
        err := ctx.Err()
         fmt.Println("server:", err)
         internalError := http.StatusInternalServerError
         http.Error(w, err.Error(), internalError)
@@ -189,7 +205,7 @@ cancellation.