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

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

在處理程序之后訪問 HTTP 請求上下文

在處理程序之后訪問 HTTP 請求上下文

Go
臨摹微笑 2023-02-21 16:45:02
在我的日志記錄中間件(鏈中的第一個)中,我需要訪問一些上下文,這些上下文是在鏈下的某些 auth 中間件中編寫的,并且僅在執行處理程序本身之后。旁注:需要首先調用日志記錄中間件,因為我需要記錄請求的持續時間,包括在中間件中花費的時間。此外,當權限不足時,auth 中間件能夠中止請求。在那種情況下,我還需要記錄失敗的請求。我的問題是從指針讀取上下文http.Request不會返回我期望它具有的身份驗證數據。請參閱下面的示例:package mainimport (    "context"    "fmt"    "net/http"    "time")const (    contextKeyUsername = "username")func authMiddleware(next http.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        ctx := r.Context()        ctx = context.WithValue(ctx, contextKeyUsername, "user123")        next.ServeHTTP(w, r.WithContext(ctx))    })}func logMiddleware(next http.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        defer func(start time.Time) {            ctx := r.Context()            username := ctx.Value(contextKeyUsername)            if username != nil {                fmt.Printf("user %s has accessed %s, took %d\n", username,                    r.URL.Path, time.Since(start).Milliseconds())            } else {                fmt.Printf("annonyous has accessed %s, took %d\n",                    r.URL.Path, time.Since(start).Milliseconds())            }        }(time.Now())        next.ServeHTTP(w, r)    })}func welcome(w http.ResponseWriter, r *http.Request) {    ctx := r.Context()    username := ctx.Value(contextKeyUsername)    if username != nil {        fmt.Fprintf(w, fmt.Sprintf("hello %s", username.(string)))    } else {        fmt.Fprintf(w, "hello")    }}func main() {    mux := http.NewServeMux()    mux.HandleFunc("/welcome", welcome)    chain := logMiddleware(authMiddleware(mux))    http.ListenAndServe(":5050", chain)}雖然 get 請求127.0.0.1:5050/welcome確實返回了預期的字符串hello user123,但日志的輸出是:annonyous has accessed /welcome, took 0由于請求是作為指針傳遞的,我預計在執行延遲時,上下文將包含預期username值。我在這里錯過了什么?
查看完整描述

1 回答

?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

WithContext返回請求的淺表副本,即創建的請求與從中讀取上下文的authMiddleware請求不同。logMiddleware

您可以讓根中間件(在本例中為logMiddleware)創建帶值的上下文和淺請求副本,但不是普通字符串在上下文中存儲非零指針authMiddleware,然后使用指針間接分配指針指向的值,然后logMiddleware,在next退出后,可以取消引用該指針以訪問該值。

并且為了避免不愉快的取消引用,您可以使用指向帶有字符串字段的結構的指針,而不是指向字符串的指針。

type ctxKey uint8


const userKey ctxKey = 0


type user struct{ name string }


func logMiddleware(next http.Handler) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        u := new(user)

        r = r.WithContext(context.WithValue(r.Context(), userKey, u))


        defer func(start time.Time) {

            if u.name != "" {

                fmt.Printf("user %s has accessed %s, took %s\n", u.name, r.URL.Path, time.Since(start))

            } else {

                fmt.Printf("annonyous has accessed %s, took %s\n", r.URL.Path, time.Since(start))

            }

        }(time.Now())


        next.ServeHTTP(w, r)

    })

}

func authMiddleware(next http.Handler) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        if u, ok := r.Context().Value(userKey).(*user); ok {

            u.name = "user123"

        }

        next.ServeHTTP(w, r)

    })

}

func welcome(w http.ResponseWriter, r *http.Request) {

    if u, ok := r.Context().Value(userKey).(*user); ok && u.name != "" {

        fmt.Fprintf(w, "hello %s", u.name)

    } else {

        fmt.Fprintf(w, "hello")

    }

}

https://go.dev/play/p/N7vmjQ7iLM1


查看完整回答
反對 回復 2023-02-21
  • 1 回答
  • 0 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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