我正在嘗試通過中間件模式自定義請求管道,代碼如下: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根據(jù)輸出,值可以從 parent 傳遞給 child ,而如果 child 添加一些東西到 context ,它對 parent 是不可見的我如何將價值從子中間件傳播到父中間件?
1 回答

白豬掌柜的
TA貢獻1893條經(jīng)驗 獲得超10個贊
您正在做的是創(chuàng)建一個指向修改后的 http.Request viaWithContext
方法的新指針。因此,如果您將它傳遞給鏈中的下一個中間件,一切都會按預(yù)期工作,因為您將這個新指針作為參數(shù)傳遞。如果要修改請求并使其對持有指向它的指針的人可見,則需要取消引用指針并設(shè)置修改后的值。
所以在你的“孩子”中間件而不是:
r = r.WithContext(ctx)
只需執(zhí)行以下操作:
*r = *r.WithContext(ctx)
- 1 回答
- 0 關(guān)注
- 108 瀏覽
添加回答
舉報
0/150
提交
取消