介绍 —— Introduction

在 Go 服务器中,每个输入请求都有它自己的 goroutine 处理。请求处理器通常会启用额外的 goroutine 去访问像数据库或 RPC 服务这种后端程序。 一批工作在一个请求上的 goroutine 通常需要访问 请求限定值( request-specific values ),比如终端用户的身份,验证 token ,请求的 deadline 。当一个请求被取消或超时,在这个请求上工作的所有 goroutine 都应该很快退出。这样系统就可以回收他们正在使用的资源。
在 Google ,我们开发了一个context包,它让跨 API 边界向包含在一个请求内的所有 goroutine 传递请求范围值( request-scope values ),取消信号,deadline 变得十分简单。
这个包现在公开可用: 。
这篇文档提供一个完全可运行的例子来讲述这个包如何使用。

In Go servers, each incoming request is handled in its own goroutine. Request handlers often start additional goroutines to access backends such as databases and RPC services. The set of goroutines working on a request typically needs access to request-specific values such as the identity of the end user, authorization tokens, and the request’s deadline. When a request is canceled or times out, all the goroutines working on that request should exit quickly so the system can reclaim any resources they are using.

At Google, we developed a context package that makes it easy to pass request-scoped values, cancellation signals, and deadlines across API boundaries to all the goroutines involved in handling a request. The package is publicly available as . This article describes how to use the package and provides a complete working example.

Context

context 包的核心是 Context 类型:

The core of the context package is the Context type:

  1. // A Context carries a deadline, cancellation signal, and request-scoped values
  2. // across API boundaries. Its methods are safe for simultaneous use by multiple
  3. // goroutines.
  4. // Context 携带一个跨 API 边界的 deadline ,取消信号以及 请求范围值。
  5. // 它的方法是线程安全的,可供多个 goroutine 同时使用
  6. type Context interface {
  7. // Done returns a channel that is closed when this Context is canceled
  8. // or times out.
  9. // 当这个 Context 被取消或超时时,Done 返回一个关闭的 channel
  10. Done() <-chan struct{}
  11. // Err indicates why this context was canceled, after the Done channel
  12. // is closed.
  13. // 在 Done channel 被关闭后,Err 表明为什么这个 Context 被取消
  14. Err() error
  15. // Deadline returns the time when this Context will be canceled, if any.
  16. // Deadline 返回这个 Context 将被取消的时间(如果有的话)
  17. Deadline() (deadline time.Time, ok bool)
  18. // Value returns the value associated with key or nil if none.
  19. // Value 返回 key 关联的值,如果没有就返回 nil
  20. Value(key interface{}) interface{}
  21. }

(这个描述是相对精简的; 中描述更权威)

(This description is condensed; the is authoritative.)

Done 方法返回一个 channel ,这个 channel 充当了 Context 运行函数的取消信号:当这个 channel 关闭时,这些函数应该放弃手头的工作并返回。Err方法返回一个 error 表明该 Context 为什么被取消。Go Concurrency Patterns: Pipelines and cancellation(本人渣翻:Go 并发模式:pipeline 和撤销)这篇文章更详细讨论 Done channel 的常规用法。

The Done method returns a channel that acts as a cancellation signal to functions running on behalf of the Context: when the channel is closed, the functions should abandon their work and return. The Err method returns an error indicating why the Context was canceled. The Pipelines and Cancellation article discusses the Done channel idiom in more detail.

Context没有Cancel方法的原因跟Donechannel 只可用于接收的原因相同:收到取消信号的函数通常不是发送该信号的函数。更具体些,当父操作为子操作启动 goroutine 后,这些子操作不应该能够取消父操作。相反WithCanel函数(在下面讨论)提供了一个方式去取消新Context值。

A Context does not have a Cancel method for the same reason the Done channel is receive-only: the function receiving a cancellation signal is usually not the one that sends the signal. In particular, when a parent operation starts goroutines for sub-operations, those sub-operations should not be able to cancel the parent. Instead, the WithCancel function (described below) provides a way to cancel a new Context value.

Context是线程安全的,可供多个 goroutine 同时使用。代码可以传递一个单 Context 给任意数量的 goroutine,也可以取消那个 Context 通知那些 goroutine 。

A Context is safe for simultaneous use by multiple goroutines. Code can pass a single Context to any number of goroutines and cancel that Context to signal all of them.

Deadline方法允许函数确定是否他自己需要开始工作;如果剩余时间太少,工作可能并不值得。代码也可以用deadline去给I/O操作设置超时时间。

The Deadline method allows functions to determine whether they should start work at all; if too little time is left, it may not be worthwhile. Code may also use a deadline to set timeouts for I/O operations.

Value使得Context可以携带 请求范围数据(request-scoped data)。其中的数据必须是线程安全的,这样可以让多个 goroutine 同时操作。

Value allows a Context to carry request-scoped data. That data must be safe for simultaneous use by multiple goroutines.

派生 context —— Derived contexts

context包提供了从已有 context 派生出新 context 值的功能。这些值构成了树结构,当一个 Context 被取消时,所有 从它派生的 Context 也会被取消。

The context package provides functions to derive new Context values from existing ones. These values form a tree: when a Context is canceled, all Contexts derived from it are also canceled.

Backgroud是所有Context树的根,它永远不会被取消:

Background is the root of any Context tree; it is never canceled:

  1. // Background returns an empty Context. It is never canceled, has no deadline,
  2. // and has no values. Background is typically used in main, init, and tests,
  3. // and as the top-level Context for incoming requests.
  4. // Background 返回一个空 Context。它没有 deadline、没有值,永远不会被取消。
  5. // Background 通常用在 main、init 和 test 中,也作为输入请求的顶层 Context
  6. func Background() Context

WithCanel 和 WithTimeout 返回派生的 Context 值,这个Context 会比它的父 Context 更快被取消。该 Context通常关联到一个输入请求,在请求处理器返回时被取消。WithCanel 在使用多副本时取消冗余请求也很有用。WithTimeOut 可以用于给后端服务器的请求设置一个 deadline :

WithCancel and WithTimeout return derived Context values that can be canceled sooner than the parent Context. The Context associated with an incoming request is typically canceled when the request handler returns. WithCancel is also useful for canceling redundant requests when using multiple replicas. WithTimeout is useful for setting a deadline on requests to backend servers:

  1. // WithCancel returns a copy of parent whose Done channel is closed as soon as
  2. // parent.Done is closed or cancel is called.
  3. // WithCanel 返回父值的副本
  4. // 一旦父级的 Done 被关闭或 cancel 被调用,它的 Done channel 与父级一样被立即关闭
  5. func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
  6. // A CancelFunc cancels a Context.
  7. // CancelFunc 用于取消一个 Context
  8. type CancelFunc func()
  9. // WithTimeout returns a copy of parent whose Done channel is closed as soon as
  10. // parent.Done is closed, cancel is called, or timeout elapses. The new
  11. // Context's Deadline is the sooner of now+timeout and the parent's deadline, if
  12. // any. If the timer is still running, the cancel function releases its
  13. // resources.
  14. // WithTimeout 返回父值的副本
  15. // 一旦父级的 Done 被关闭 或 cancel 被调用,或者触发超时。
  16. // 它的 Done channel 与父级一样立即被关闭
  17. // 新 Context 的 Deadline 是当前时间 + 超时时间与父 Context 的 Deadline 中的较早者。
  18. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

WithValue 提供了一种方式,可以把请求范围值关联到一个Context:

WithValue provides a way to associate request-scoped values with a Context:

  1. // WithValue returns a copy of parent whose Value method returns val for key.
  2. // WithValue 返回父值的副本
  3. // 它的 Value 方法返回 key 对应的值
  4. func WithValue(parent Context, key interface{}, val interface{}) Context

了解如何使用 context 包的最好方式是学习一个可运行的例子。

The best way to see how to use the context package is through a worked example.

例子:Google Web 搜索 —— Example: Google Web Search

我们的例子是一个 Http 服务器,它处理类似于/search?q=golang&timeout=1s这样的 URL ,这个例子中,转发查询 golang给 Google Web Search API 并渲染结果。timeout参数告诉服务器在经过这么多事件后取消请求。

Our example is an HTTP server that handles URLs like /search?q=golang&timeout=1s by forwarding the query “golang” to the Google Web Search API and rendering the results. The timeout parameter tells the server to cancel the request after that duration elapses.

代码分为三个包:

  • server 提供main函数和对/search的 handler 。
  • userip 提供从一个请求中提取用户 IP 并关联到 Context 的函数。
  • google 提供Search函数,用于给 Google 发送查询。

    The code is split across three packages:

    • server provides the main function and the handler for /search.
    • userip provides functions for extracting a user IP address from a request and associating it with a Context.
    • google provides the Search function for sending a query to Google.

server程序 —— The server program

server 程序通过提供 golang 的前几个 Google 搜索结果来处理像 /search?q=golang 这样的请求。它注册 handleSearch 去处理 /search 端点。handler 创建一个名为 ctx 的初始 Context 并在 handler 返回的时候取消掉。如果请求包含 timeoutURL 参数,在时间超时的时候 Context 会自动取消:

The server program handles requests like /search?q=golang by serving the first few Google search results for golang. It registers handleSearch to handle the /search endpoint. The handler creates an initial Context called ctx and arranges for it to be canceled when the handler returns. If the request includes the timeout URL parameter, the Context is canceled automatically when the timeout elapses:

  1. func handleSearch(w http.ResponseWriter, req *http.Request) {
  2. // ctx is the Context for this handler. Calling cancel closes the
  3. // ctx.Done channel, which is the cancellation signal for requests
  4. // started by this handler.
  5. var (
  6. ctx context.Context
  7. cancel context.CancelFunc
  8. )
  9. timeout, err := time.ParseDuration(req.FormValue("timeout"))
  10. if err == nil {
  11. // The request has a timeout, so create a context that is
  12. // canceled automatically when the timeout expires.
  13. ctx, cancel = context.WithTimeout(context.Background(), timeout)
  14. } else {
  15. ctx, cancel = context.WithCancel(context.Background())
  16. }
  17. defer cancel() // Cancel ctx as soon as handleSearch returns.

handler 从请求中提取查询词,调用 userip 包去提取请求的客户端 IP。后端请求需要客户端的 IP 地址,所以 handleSearch 将其附在 ctx 上:

The handler extracts the query from the request and extracts the client’s IP address by calling on the userip package. The client’s IP address is needed for backend requests, so handleSearch attaches it to ctx:

  1. // Check the search query.
  2. query := req.FormValue("q")
  3. if query == "" {
  4. http.Error(w, "no query", http.StatusBadRequest)
  5. return
  6. }
  7. // Store the user IP in ctx for use by code in other packages.
  8. userIP, err := userip.FromRequest(req)
  9. if err != nil {
  10. http.Error(w, err.Error(), http.StatusBadRequest)
  11. return
  12. }
  13. ctx = userip.NewContext(ctx, userIP)

handler 带着 ctx 和查询词调用 google.Search:

The handler calls google.Search with ctx and the query:

  1. // Run the Google search and print the results.
  2. start := time.Now()
  3. results, err := google.Search(ctx, query)
  4. elapsed := time.Since(start)

如果搜索成功,handler 会渲染结果:

If the search succeeds, the handler renders the results:

  1. if err := resultsTemplate.Execute(w, struct {
  2. Results google.Results
  3. Timeout, Elapsed time.Duration
  4. }{
  5. Results: results,
  6. Timeout: timeout,
  7. Elapsed: elapsed,
  8. }); err != nil {
  9. log.Print(err)
  10. return
  11. }

userip 包 —— Package userip

userip 包提供了从一个请求中提取用户 IP 地址并将其关联到一个 Context 的函数。Context 提供键值对映射,键和值的类型都是 interface{}。键类型必须支持相等,并且值必须安全,可供多个goroutine同时使用。像 userip 这样的包隐藏了映射的细节,并提供了对特定 Context 值的强类型访问。

The userip package provides functions for extracting a user IP address from a request and associating it with a Context. A Context provides a key-value mapping, where the keys and values are both of type interface{}. Key types must support equality, and values must be safe for simultaneous use by multiple goroutines. Packages like userip hide the details of this mapping and provide strongly-typed access to a specific Context value.

为了避免键冲突,userip 定义了一个未导出类型 key 并使用该类型的一个值作为 context 的键:

To avoid key collisions, userip defines an unexported type key and uses a value of this type as the context key:

  1. // The key type is unexported to prevent collisions with context keys defined in
  2. // other packages.
  3. type key int
  4. // userIPkey is the context key for the user IP address. Its value of zero is
  5. // arbitrary. If this package defined other context keys, they would have
  6. // different integer values.
  7. const userIPKey key = 0

FromRequest 从 http.Request 中提取 userIP 值:

FromRequest extracts a userIP value from an http.Request:

  1. func FromRequest(req *http.Request) (net.IP, error) {
  2. ip, _, err := net.SplitHostPort(req.RemoteAddr)
  3. if err != nil {
  4. return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
  5. }

NewContext 返回一个携带了 userIP值的新 Context :

NewContext returns a new Context that carries a provided userIP value:

  1. func NewContext(ctx context.Context, userIP net.IP) context.Context {
  2. return context.WithValue(ctx, userIPKey, userIP)
  3. }

FromContext 从一个 Context 中提取 userIP:

FromContext extracts a userIP from a Context:

  1. func FromContext(ctx context.Context) (net.IP, bool) {
  2. // ctx.Value returns nil if ctx has no value for the key;
  3. // the net.IP type assertion returns ok=false for nil.
  4. userIP, ok := ctx.Value(userIPKey).(net.IP)
  5. return userIP, ok
  6. }

google 包 —— Package google

[google.Search](https://go.dev/blog/context/google/google.go) 函数向 Google Web Search API 发出 HTTP 请求,并解析 JSON 编码的结果。它接受 Context 参数ctx,在请求执行过程中 ctx.Done 被关闭会立即返回。

The google.Search function makes an HTTP request to the Google Web Search API and parses the JSON-encoded result. It accepts a Context parameter ctx and returns immediately if ctx.Done is closed while the request is in flight.

Google Web Search API 请求的查询参数包括搜索查询词和用户 IP :

The Google Web Search API request includes the search query and the user IP as query parameters:

  1. func Search(ctx context.Context, query string) (Results, error) {
  2. // Prepare the Google Search API request.
  3. req, err := http.NewRequest("GET", "https://ajax.googleapis.com/ajax/services/search/web?v=1.0", nil)
  4. if err != nil {
  5. return nil, err
  6. }
  7. q := req.URL.Query()
  8. q.Set("q", query)
  9. // If ctx is carrying the user IP address, forward it to the server.
  10. // Google APIs use the user IP to distinguish server-initiated requests
  11. // from end-user requests.
  12. if userIP, ok := userip.FromContext(ctx); ok {
  13. q.Set("userip", userIP.String())
  14. }
  15. req.URL.RawQuery = q.Encode()

Search使用了一个辅助函数 httpDo。httpDo 发出 HTTP 请求。在处理请求或响应时,如果ctx.Done被关闭则取消该请求。

Search uses a helper function, httpDo, to issue the HTTP request and cancel it if ctx.Done is closed while the request or response is being processed. Search passes a closure to httpDo handle the HTTP response:

  1. var results Results
  2. err = httpDo(ctx, req, func(resp *http.Response, err error) error {
  3. if err != nil {
  4. return err
  5. }
  6. defer resp.Body.Close()
  7. // Parse the JSON search result.
  8. // https://developers.google.com/web-search/docs/#fonje
  9. var data struct {
  10. ResponseData struct {
  11. Results []struct {
  12. TitleNoFormatting string
  13. URL string
  14. }
  15. }
  16. }
  17. if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
  18. return err
  19. }
  20. for _, res := range data.ResponseData.Results {
  21. results = append(results, Result{Title: res.TitleNoFormatting, URL: res.URL})
  22. }
  23. return nil
  24. })
  25. // httpDo waits for the closure we provided to return, so it's safe to
  26. // read results here.
  27. return results, err

httpDo 函数在一个新 goroutine 中发起 HTTP 请求并处理响应。如果在 goroutine 退出前 ctx.Done 被关闭,就取消该请求。

The httpDo function runs the HTTP request and processes its response in a new goroutine. It cancels the request if ctx.Done is closed before the goroutine exits:

  1. func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
  2. // Run the HTTP request in a goroutine and pass the response to f.
  3. c := make(chan error, 1)
  4. req = req.WithContext(ctx)
  5. go func() { c <- f(http.DefaultClient.Do(req)) }()
  6. select {
  7. case <-ctx.Done():
  8. <-c // Wait for f to return.
  9. return ctx.Err()
  10. case err := <-c:
  11. return err
  12. }
  13. }

为 Context 适配代码 —— Adapting code for Contexts

许多服务器框架提供用于承载请求范围值的包和类型。我们可以定义 Context 接口的新实现,从而在使用现有框架的代码和需要 Context 参数的代码之间架起桥梁。

Many server frameworks provide packages and types for carrying request-scoped values. We can define new implementations of the Context interface to bridge between code using existing frameworks and code that expects a Context parameter.

例如 Gorilla 的 github.com/gorilla/context 包允许 handler 通过提供从 HTTP 请求到键值对的映射,将数据与传入请求相关联。在 gorilla.go 中,我们提供了一个 Context 实现,其Value 方法返回与 Gorilla 包中的特定 HTTP 请求相关联的值。

For example, Gorilla’s github.com/gorilla/context package allows handlers to associate data with incoming requests by providing a mapping from HTTP requests to key-value pairs. In gorilla.go, we provide a Context implementation whose Value method returns the values associated with a specific HTTP request in the Gorilla package.

其他软件包提供了与 Context 类似的取消功能。例如,Tomb 提供了一个Kill方法,通过关闭 Dying channel 发出取消信号。Tomb 还提供了等待这些 goroutine 退出的方法,类似于sync.WaitGroup。在 tomb.go 中,我们提供了一个 Context 实现,当其父 Context 被取消或提供的 Tomb 被终止时,该 Context 会被取消。

Other packages have provided cancellation support similar to Context. For example, Tomb provides a Kill method that signals cancellation by closing a Dying channel. Tomb also provides methods to wait for those goroutines to exit, similar to sync.WaitGroup. In tomb.go, we provide a Context implementation that is canceled when either its parent Context is canceled or a provided Tomb is killed.

总结 —— Conclusion

在 Google ,我们要求 Go 编程者把 Context 参数作为第一个参数传递给传入和传出请求之间调用路径上的每个函数。这使得许多不同团队开发的 Go 代码能够很好地互操作。它提供了对超时和取消的简单控制,并确保安全凭证等关键值在 Go 中正确传递。

At Google, we require that Go programmers pass a Context parameter as the first argument to every function on the call path between incoming and outgoing requests. This allows Go code developed by many different teams to interoperate well. It provides simple control over timeouts and cancellation and ensures that critical values like security credentials transit Go programs properly.

想要基于 Context 构建的服务器框架应该提供 Context 的实现,这样就可以在它们的包和需要 Context 参数的包之间架起桥梁。这样他们的客户端库将接受来自调用代码的 Context 。通过为 请求范围数据 和 取消 建立公共接口,Context 使包开发者更容易共享创建可扩展服务的代码。

Server frameworks that want to build on Context should provide implementations of Context to bridge between their packages and those that expect a Context parameter. Their client libraries would then accept a Context from the calling code. By establishing a common interface for request-scoped data and cancellation, Context makes it easier for package developers to share code for creating scalable services.