第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

正確使用 go context.Context

正確使用 go context.Context

Go
ibeautiful 2021-10-18 11:03:51
我剛剛閱讀了這篇文章:在 Go 中構(gòu)建您自己的 Web 框架,為了在處理程序之間共享值,我選擇了context.Context并以以下方式使用它來(lái)跨處理程序和中間件共享值: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 快所以我的問(wèn)題是:這種方法安全嗎?真的有必要按照我的方式推遲 c.cancel() 函數(shù)嗎?我可以使用它來(lái)實(shí)現(xiàn)自定義 Web 框架,通過(guò)使用 struct 之類的控制器與模型共享值嗎?
查看完整描述

3 回答

?
慕哥9229398

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊

注意:go 1.7.0-rc2 確實(shí)闡明了如何釋放與上下文相關(guān)的資源(Sameer Ajmani):

一些用戶沒(méi)有意識(shí)到Context用 a創(chuàng)建 aCancelFunc會(huì)將子樹(shù)附加到父級(jí),并且在CancelFunc調(diào)用 或取消父級(jí)之前不會(huì)釋放該子樹(shù)。

在包文檔中盡早明確這一點(diǎn),以便人們了解這個(gè)包有正確的概念模型。

該文檔現(xiàn)在包括:

對(duì)服務(wù)器的傳入請(qǐng)求應(yīng)創(chuàng)建Context,而對(duì)服務(wù)器的傳出調(diào)用應(yīng)接受Context.
它們之間的函數(shù)調(diào)用鏈必須傳播Context,可選擇將其替換為Context使用WithCancel、WithDeadlineWithTimeout、 或 所創(chuàng)建的派生WithValue。
這些Context值形成一棵樹(shù):當(dāng) aContext被取消時(shí),所有Contexts從它派生的也被取消。

WithCancel,WithDeadlineWithTimeout函數(shù)返回一個(gè)派生ContextCancelFunc。
調(diào)用CancelFunc取消新的Context和從它派生的任何上下文,Context從父樹(shù)的樹(shù)中刪除,并停止任何相關(guān)的計(jì)時(shí)器。在父級(jí)被取消或計(jì)時(shí)器觸發(fā)之前,
未能調(diào)用CancelFunc泄漏相關(guān)資源Context。


查看完整回答
反對(duì) 回復(fù) 2021-10-18
  • 3 回答
  • 0 關(guān)注
  • 248 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)