gpt4 book ai didi

concurrency - 正确使用go context.Context

转载 作者:IT王子 更新时间:2023-10-29 01:42:39 31 4
gpt4 key购买 nike

我刚读了这篇文章:Build You Own Web Framework In Go为了在处理程序之间共享值,我选择了 context.Context我通过以下方式使用它在处理程序和中间件之间共享值:

type appContext struct {
db *sql.DB
ctx context.Context
cancel context.CancelFunc
}


func (c *appContext)authHandler(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request {
defer c.cancel() //this feels weird
authToken := r.Header.Get("Authorization") // this fakes a form
c.ctx = getUser(c.ctx, c.db, authToken) // this also feels weird
next.ServeHTTP(w, r)
}

return http.HandlerFunc(fn)
}

func (c *appContext)adminHandler(w http.ResponseWriter, r *http.Request) {
defer c.cancel()
user := c.ctx.Value(0).(user)
json.NewEncoder(w).Encode(user)
}

func getUser(ctx context.Context, db *sql.DB, token string) context.Context{
//this function mimics a database access
return context.WithValue(ctx, 0, user{Nome:"Default user"})
}

func main() {
db, err := sql.Open("my-driver", "my.db")
if err != nil {
panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
appC := appContext{db, ctx, cancel}
//....
}

一切正常,处理程序加载速度比使用 gorilla/context 快 所以我的问题是:

  1. 这种方法安全吗?
  2. 是否真的有必要按照我的方式延迟 c.cancel() 函数?
  3. 我可以使用它来实现自定义 Web 框架,方法是使用 struct 等 Controller 与模型共享值吗?

最佳答案

注意:go 1.7.0-rc2 确实澄清了一点 how to release resources associated with Contexts ( Sameer Ajmani ):

Some users don't realize that creating a Context with a CancelFunc attaches a subtree to the parent, and that that subtree is not released until the CancelFunc is called or the parent is canceled.

Make this clear early in the package docs, so that people learning about this package have the right conceptual model.

documentation now includes :

Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context.
The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue.
These Context values form a tree: when a Context is canceled, all Contexts derived from it are also canceled.

The WithCancel, WithDeadline, and WithTimeout functions return a derived Context and a CancelFunc.
Calling the CancelFunc cancels the new Context and any Contexts derived from it, removes the Context from the parent's tree, and stops any associated timers.
Failing to call the CancelFunc leaks the associated resources until the parent Context is canceled or the timer fires.

关于concurrency - 正确使用go context.Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30928002/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com