在线文档  >   Golang练习   >   上下文(Context)

在上一个例子中,我们介绍了如何设置一个简单的 HTTP 服务器。HTTP 服务器非常适用于演示如何使用 context.Context 来控制取消操作。Context 可以携带截止时间、取消信号和其他 API 范围的值,供跨越边界与 goroutine 使用。

package main

import (
    "fmt"
    "net/http"
    "time"
)

func hello(w http.ResponseWriter, req *http.Request) {

    // 由 `net/http` 机制为每个请求创建一个 `context.Context`,并可通过 `Context()` 函数获取。
    ctx := req.Context()
    fmt.Println("server: hello handler started")
    defer fmt.Println("server: hello handler ended")

    // 等待几秒钟后再向客户端发送响应。
    // 这可以模拟服务器正在进行的某些工作。
    // 在工作时,可以关注上下文的 `Done()` 通道,以获取需要取消工作并尽快返回的信号。
    select {
    case <-time.After(10 * time.Second):
        fmt.Fprintf(w, "hello\n")
    case <-ctx.Done():
        // 上下文的 `Err()` 方法返回一个错误,解释了为什么 `Done()` 通道被关闭。
        err := ctx.Err()
        fmt.Println("server:", err)
        internalError := http.StatusInternalServerError
        http.Error(w, err.Error(), internalError)
    }
}

func main() {

    // 像以前一样,在“/hello”路由上注册处理程序,并开始服务。
    http.HandleFunc("/hello", hello)
    http.ListenAndServe(":8090", nil)
}

运行结果如下:

# 在后台运行服务器。
$ go run context-in-http-servers.go &

# 模拟客户端发出 `/hello` 请求, 在服务端开始处理后,按下 Ctrl+C 以发出取消信号
# cancellation.
$ curl localhost:8090/hello
server: hello handler started
^C
server: context canceled
server: hello handler ended