亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將值從子中間件傳播到父中間件?

如何將值從子中間件傳播到父中間件?

Go
哈士奇WWW 2022-12-19 11:49:22
我正在嘗試通過中間件模式自定義請求管道,代碼如下:func helloHandler(w http.ResponseWriter, r *http.Request) {    fmt.Println("Hello, middleware!")}func middleware1(next http.HandlerFunc) func(w http.ResponseWriter, r *http.Request) {    return func(w http.ResponseWriter, r *http.Request) {        fmt.Println("[START] middleware1")        ctx := r.Context()        ctx = context.WithValue(ctx, middleware1Key, middleware1Value)        r = r.WithContext(ctx)        next(w, r)        fmt.Println("[END] middleware1")        ctx = r.Context()        if val, ok := ctx.Value(middleware2Key).(string); ok {            fmt.Printf("Value from middleware2 %s \n", val)        }    }}func middleware2(next http.HandlerFunc) func(w http.ResponseWriter, r *http.Request) {    return func(w http.ResponseWriter, r *http.Request) {        fmt.Println("[START] middleware2")        ctx := r.Context()        if val, ok := ctx.Value(middleware1Key).(string); ok {            fmt.Printf("Value from middleware1 %s \n", val)        }        ctx = context.WithValue(ctx, middleware2Key, middleware2Value)        r = r.WithContext(ctx)        next(w, r)        fmt.Println("[END] middleware2")    }}func main() {    mux := http.NewServeMux()    middlewares := newMws(middleware1, middleware2)    mux.HandleFunc("/hello", middlewares.then(helloHandler))    if err := http.ListenAndServe(":8080", mux); err != nil {        panic(err)    }}輸出是:[START] middleware1[START] middleware2Value from middleware1 middleware1ValueHello, middleware![END] middleware2[END] middleware1根據輸出,值可以從 parent 傳遞給 child ,而如果 child 添加一些東西到 context ,它對 parent 是不可見的我如何將價值從子中間件傳播到父中間件?
查看完整描述

1 回答

?
白豬掌柜的

TA貢獻1893條經驗 獲得超10個贊

您正在做的是創建一個指向修改后的 http.Request viaWithContext方法的新指針。因此,如果您將它傳遞給鏈中的下一個中間件,一切都會按預期工作,因為您將這個新指針作為參數傳遞。如果要修改請求并使其對持有指向它的指針的人可見,則需要取消引用指針并設置修改后的值。

所以在你的“孩子”中間件而不是:

r = r.WithContext(ctx)

只需執行以下操作:

*r = *r.WithContext(ctx)


查看完整回答
反對 回復 2022-12-19
  • 1 回答
  • 0 關注
  • 117 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號