我正在使用背景關系在我的 go rest 應用程式的中間件中附加用戶有效負載(特別是 userId)
// middleware
// attaching payload to the request context
claimsWithPayload, _ := token.Claims.(*handlers.Claims)
ctx := context.WithValue(r.Context(), "userid", claimsWithPayload.Id)
req := r.WithContext(ctx)
h := http.HandlerFunc(handler)
h.ServeHTTP(w, req)
稍后在 http 處理程式中,我需要提取該用戶 ID,string/integer
但 context().Value() 回傳一個介面{}
// handler
a := r.Context().Value("userid") // THIS returns an interface{}
response := []byte("Your user ID is" a) // ?? how do I use it as a string/integer??
w.Write(response)
uj5u.com熱心網友回復:
您可以使用型別斷言來獲取背景關系值作為其基礎型別:
a := r.Context().Value("userid").(string)
如果中間件存盤的值不是字串,或者其他東西將背景關系鍵設定為不是字串的東西,則會出現恐慌。為了防止這種情況,你永遠不應該使用內置型別作為背景關系鍵,而是定義你自己的型別并使用它:
type contextKey string
const userIDKey contextKey = "userid"
...
ctx := context.WithValue(r.Context(), userIDKey, claimsWithPayload.Id)
...
a := r.Context().Value(userIDKey).(string)
因為contextKey和userIDKey未匯出,所以只有您的包可以從背景關系讀取或寫入此值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409657.html
標籤:
