在 Go http包的Server中,每个请求在都有一个对应的 goroutine 去处理。请求处理函数一般会启动额外的 goroutine 用来访问后端服务,好比数据库和RPC服务。用来处理一个请求的 goroutine 一般须要访问一些与请求特定的数据,好比终端用户的身份认证信息、验证相关的token、请求的截止时间。 当一个请求被取消或超时时,全部用来处理该请求的 goroutine 都应该迅速退出,而后系统才能释放这些 goroutine 占用的资源。git
在Google 内部,咱们开发了 Context
包,专门用来简化 对于处理单个请求的多个 goroutine 之间与请求域的数据、取消信号、截止时间等相关操做,这些操做可能涉及多个 API 调用。你能够经过 go get golang.org/x/net/context
命令获取这个包。本文要讲的就是若是使用这个包,同时也会提供一个完整的例子。程序员
本文内容涉及到了 done channel,若是你不了解这个概念,那么请先阅读 "Go语言并发模型:像Unix Pipe那样使用channel"。github
因为访问 golang.org/x/net/context
须要梯子,你能够访问它在 github 上的 mirror。
若是要下载本文中的代码,能够查看文章末尾的“相关连接”环节。golang
context 包的核心是 struct Context,声明以下:web
// A Context carries a deadline, cancelation signal, and request-scoped values // across API boundaries. Its methods are safe for simultaneous use by multiple // goroutines. type Context interface { // Done returns a channel that is closed when this `Context` is canceled // or times out. Done() <-chan struct{} // Err indicates why this Context was canceled, after the Done channel // is closed. Err() error // Deadline returns the time when this Context will be canceled, if any. Deadline() (deadline time.Time, ok bool) // Value returns the value associated with key or nil if none. Value(key interface{}) interface{} }
注意: 这里咱们对描述进行了简化,更详细的描述查看 godoc:contextajax
Done
方法返回一个 channel,这个 channel 对于以 Context
方式运行的函数而言,是一个取消信号。当这个 channel 关闭时,上面提到的这些函数应该终止手头的工做并当即返回。 以后,Err
方法会返回一个错误,告知为何 Context
被取消。关于 Done
channel 的更多细节查看上一篇文章 "Go语言并发模型:像Unix Pipe那样使用channel"。数据库
一个 Context
不能拥有 Cancel
方法,同时咱们也只能 Done
channel 接收数据。背后的缘由是一致的:接收取消信号的函数和发送信号的函数一般不是一个。 一个典型的场景是:父操做为子操做操做启动 goroutine,子操做也就不能取消父操做。 做为一个折中,WithCancel
函数 (后面会细说) 提供了一种取消新的 Context
的方法。json
Context
对象是线程安全的,你能够把一个 Context
对象传递给任意个数的 gorotuine,
对它执行 取消 操做时,全部 goroutine 都会接收到取消信号。segmentfault
Deadline
方法容许函数肯定它们是否应该开始工做。若是剩下的时间太少,也许这些函数就不值得启动。代码中,咱们也可使用 Deadline
对象为 I/O 操做设置截止时间。后端
Value
方法容许 Context
对象携带request做用域的数据,该数据必须是线程安全的。
context 包提供了一些函数,协助用户从现有的 Context
对象建立新的 Context
对象。
这些 Context
对象造成一棵树:当一个 Context
对象被取消时,继承自它的全部 Context
都会被取消。
Background
是全部 Context
对象树的根,它不能被取消。它的声明以下:
// Background returns an empty Context. It is never canceled, has no deadline, // and has no values. Background is typically used in main, init, and tests, // and as the top-level `Context` for incoming requests. func Background() Context
WithCancel
和 WithTimeout
函数 会返回继承的 Context
对象, 这些对象能够比它们的父 Context
更早地取消。
当请求处理函数返回时,与该请求关联的 Context
会被取消。 当使用多个副本发送请求时,可使用 WithCancel
取消多余的请求。 WithTimeout
在设置对后端服务器请求截止时间时很是有用。 下面是这三个函数的声明:
// WithCancel returns a copy of parent whose Done channel is closed as soon as // parent.Done is closed or cancel is called. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) // A CancelFunc cancels a Context. type CancelFunc func() // WithTimeout returns a copy of parent whose Done channel is closed as soon as // parent.Done is closed, cancel is called, or timeout elapses. The new // Context's Deadline is the sooner of now+timeout and the parent's deadline, if // any. If the timer is still running, the cancel function releases its // resources. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
WithValue
函数可以将请求做用域的数据与 Context
对象创建关系。声明以下:
// WithValue returns a copy of parent whose Value method returns val for key. func WithValue(parent Context, key interface{}, val interface{}) Context
固然,想要知道 Context
包是如何工做的,最好的方法是看一个栗子。
咱们的例子是一个 HTTP 服务,它可以将相似于 /search?q=golang&timeout=1s
的请求 转发给
Google Web Search API,而后渲染返回的结果。timeout
参数用来告诉 server 时间到时取消请求。
这个例子的代码存放在三个包里:
server:它提供 main 函数和 处理 /search
的 http handler
userip:它可以从 请求解析用户的IP,并将请求绑定到一个 Context
对象。
google:它包含了 Search 函数,用来向 Google 发送请求。
server 程序处理相似于 /search?q=golang
的请求,返回 Google API 的搜索结果。它将 handleSearch
函数注册到 /search
路由。处理函数建立一个 Context
ctx,并对其进行初始化,以保证 Context
取消时,处理函数返回。若是请求的 URL 参数中包含 timeout
,那么当 timeout
到期时, Context
会被自动取消。
handleSearch 的代码以下:
func handleSearch(w http.ResponseWriter, req *http.Request) { // ctx is the `Context` for this handler. Calling cancel closes the // ctx.Done channel, which is the cancellation signal for requests // started by this handler. var ( ctx context.Context cancel context.CancelFunc ) timeout, err := time.ParseDuration(req.FormValue("timeout")) if err == nil { // The request has a timeout, so create a `Context` that is // canceled automatically when the timeout expires. ctx, cancel = context.WithTimeout(context.Background(), timeout) } else { ctx, cancel = context.WithCancel(context.Background()) } defer cancel() // Cancel ctx as soon as handleSearch returns.
处理函数 (handleSearch) 将query 参数从请求中解析出来,而后经过 userip 包将client IP解析出来。这里 Client IP 在后端发送请求时要用到,因此 handleSearch 函数将它 attach 到 Context
对象 ctx 上。代码以下:
// Check the search query. query := req.FormValue("q") if query == "" { http.Error(w, "no query", http.StatusBadRequest) return } // Store the user IP in ctx for use by code in other packages. userIP, err := userip.FromRequest(req) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } ctx = userip.NewContext(ctx, userIP)
处理函数带着 Context
对象 ctx
和 query
调用 google.Search
,代码以下:
// Run the Google search and print the results. start := time.Now() results, err := google.Search(ctx, query) elapsed := time.Since(start)
若是搜索成功,处理函数会渲染搜索结果,代码以下:
if err := resultsTemplate.Execute(w, struct { Results google.Results Timeout, Elapsed time.Duration }{ Results: results, Timeout: timeout, Elapsed: elapsed, }); err != nil { log.Print(err) return }
userip 包提供了两个功能:
从请求解析出Client IP;
将 Client IP 关联到一个 Context
对象。
一个 Context
对象提供一个 key-value 映射,key 和 value的类型都是 interface{},可是 key 必须知足等价性(能够比较),value 必须是线程安全的。相似于 userip
的包隐藏了映射的细节,提供的是对特定 Context
类型值得强类型访问。
为了不 key 冲突,userip
定义了一个非输出类型 key
,并使用该类型的值做为 Context
的key。代码以下:
// 为了不与其余包中的 `Context` key 冲突 // 这里不输出 key 类型 (首字母小写) type key int // userIPKey 是 user IP 的 `Context` key // 它的值是随意写的。若是这个包中定义了其余 // `Context` key,这些 key 必须不一样 const userIPKey key = 0
函数 FromRequest
用来从一个 http.Request 对象中解析出 userIP:
func FromRequest(req *http.Request) (net.IP, error) { ip, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr) }
函数 NewContext
返回一个新的 Context
对象,它携带者 userIP:
func NewContext(ctx context.Context, userIP net.IP) context.Context { return context.WithValue(ctx, userIPKey, userIP) }
函数 FromContext
从一个 Context
对象中解析 userIP:
func FromContext(ctx context.Context) (net.IP, bool) { // ctx.Value returns nil if ctx has no value for the key; // the net.IP type assertion returns ok=false for nil. userIP, ok := ctx.Value(userIPKey).(net.IP) return userIP, ok }
函数 google.Search
想 Google Web Search API 发送一个 HTTP 请求,并解析返回的 JSON 数据。该函数接收一个 Context
对象 ctx 做为第一参数,在请求尚未返回时,一旦 ctx.Done
关闭,该函数也会当即返回。
Google Web Search API 请求包含 query 关键字和 user IP 两个参数。具体实现以下:
func Search(ctx context.Context, query string) (Results, error) { // Prepare the Google Search API request. req, err := http.NewRequest("GET", "https://ajax.googleapis.com/ajax/services/search/web?v=1.0", nil) if err != nil { return nil, err } q := req.URL.Query() q.Set("q", query) // If ctx is carrying the user IP address, forward it to the server. // Google APIs use the user IP to distinguish server-initiated requests // from end-user requests. if userIP, ok := userip.FromContext(ctx); ok { q.Set("userip", userIP.String()) } req.URL.RawQuery = q.Encode()
函数 Search
使用一个辅助函数 httpDo
发送 HTTP 请求,并在 ctx.Done
关闭时取消请求 (若是还在处理请求或返回)。函数 Search
传递给 httpDo
一个闭包处理 HTTP 结果。下面是具体实现:
var results Results err = httpDo(ctx, req, func(resp *http.Response, err error) error { if err != nil { return err } defer resp.Body.Close() // Parse the JSON search result. // https://developers.google.com/web-search/docs/#fonje var data struct { ResponseData struct { Results []struct { TitleNoFormatting string URL string } } } if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { return err } for _, res := range data.ResponseData.Results { results = append(results, Result{Title: res.TitleNoFormatting, URL: res.URL}) } return nil }) // httpDo waits for the closure we provided to return, so it's safe to // read results here. return results, err
函数 httpDo
在一个新的 goroutine 中发送 HTTP 请求和处理结果。若是 ctx.Done
已经关闭,而处理请求的 goroutine 还存在,那么取消请求。下面是具体实现:
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error { // Run the HTTP request in a goroutine and pass the response to f. tr := &http.Transport{} client := &http.Client{Transport: tr} c := make(chan error, 1) go func() { c <- f(client.Do(req)) }() select { case <-ctx.Done(): tr.CancelRequest(req) <-c // Wait for f to return. return ctx.Err() case err := <-c: return err } }
Context
许多服务器框架都提供了管理请求做用域数据的包和类型。咱们能够定义一个 Context
接口的实现,
将已有代码和指望 Context
参数的代码粘合起来。
举个栗子,Gorilla 框架的 github.com/gorilla/context 包容许处理函数 (handlers) 将数据和请求结合起来,他经过 HTTP 请求 到 key-value对 的映射来实现。在 gorilla.go 中,咱们提供了一个 Context
的具体实现,这个实现的 Value 方法返回的值已经与 gorilla 包中特定的 HTTP 请求关联起来。
还有一些包实现了相似于 Context
的取消机制。好比 Tomb 中有一个 Kill 方法,该方法经过关闭 名为Dying
的 channel 发送取消信号。Tomb
也提供了等待 goroutine 退出的方法,相似于 sync.WaitGroup
。在 tomb.go 中,咱们提供了一个 Context
的实现,当它的父 Context
被取消
或 一个 Tomb
对象被 kill 时,该 Context
对象也会被取消。
在 Google, 咱们要求 Go 程序员把 Context
做为第一个参数传递给 入口请求和出口请求链路上的每个函数。这种机制一方面保证了多个团队开发的 Go 项目可以良好地协做,另外一方面它是一种简单的超时和取消机制,保证了临界区数据 (好比安全凭证) 在不一样的 Go 项目中顺利传递。
若是你要在 Context
之上构建服务器框架,须要一个本身的 Context
实现,在框架与指望 Context
参数的代码之间创建一座桥梁。
固然,Client 库也须要接收一个 Context
对象。在请求做用域数据与取消之间创建了通用的接口之后,开发者使用 Context
分享代码、建立可扩展的服务都会很是方便。
原做者:Sameer Ajmani 翻译:Oscar
下期预告:Go语言并发模型:使用 select (原文连接)。
扫码关注微信公众号“深刻Go语言”