我刚刚阅读了这篇文章:在 Go 中构建您自己的 Web 框架,为了在处理程序之间共享值,我选择了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 快所以我的问题是:
这种方法安全吗?
真的有必要按照我的方式推迟 c.cancel() 函数吗?
我可以使用它来实现自定义 Web 框架,通过使用 struct 之类的控制器与模型共享值吗?
慕哥9229398
相关分类