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

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

傳入請求:帶有自定義類型字段的上下文

傳入請求:帶有自定義類型字段的上下文

Go
紅糖糍粑 2022-04-20 20:45:04
我正在使用 go 編寫一個(gè)或多或少簡單的 Web 應(yīng)用程序,它提供了一個(gè) rest api。當(dāng)請求進(jìn)來時(shí),我想將用戶的 id 臨時(shí)存儲(chǔ)在請求上下文中,它是 api 令牌的一部分。在閱讀 了一些 文章和文檔之后,我仍然很困惑如何確保使用 附加到上下文的值context.WithValue()可以在沒有類型斷言的情況下使用,而是使用某種結(jié)構(gòu)。到目前為止,這是我想出的:// RequestContext contains the application-specific information that are carried around in a request.type RequestContext interface {    context.Context    // UserID returns the ID of the user for the current request    UserID() uuid.UUID    // SetUserID sets the ID of the currently authenticated user    SetUserID(id uuid.UUID)}type requestContext struct {    context.Context           // the golang context    now             time.Time // the time when the request is being processed    userID          uuid.UUID // an ID identifying the current user}func (ctx *requestContext) UserID() uuid.UUID {    return ctx.userID}func (ctx *requestContext) SetUserID(id uuid.UUID) {    ctx.userID = id}func (ctx *requestContext) Now() time.Time {    return ctx.now}// NewRequestContext creates a new RequestContext with the current request information.func NewRequestContext(now time.Time, r *http.Request) RequestContext {    return &requestContext{        Context: r.Context(),        now:     now,    }}// RequestContextHandler is a middleware that sets up a new RequestContext and attaches it to the current request.func RequestContextHandler(next http.Handler) http.Handler {    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {        now := time.Now()        next.ServeHTTP(w, r.WithContext(NewRequestContext(now, r)))    })}我想知道如何在處理程序中訪問請求上下文的SetUserID()和UserID()函數(shù),或者是否有替代的類似方法。
查看完整描述

2 回答

?
倚天杖

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

要使用您構(gòu)建的內(nèi)容,您必須使用類型斷言:


rctx:=request.Context().(RequestContext)

如果您有一個(gè)以與您相同的方式包裝上下文的中間件,這將中斷。


另一種方法是使用基本上下文,并添加帶有私鑰的助手來訪問值:


type reqKey int


const key reqKey=iota


type RequestData struct {

   UserID uuid.UUID

   Now time.Time

}


func ContextWithRequest(ctx context.Context,req requestData) context.Context {

  return context.WithValue(ctx,key,req)

}


func GetRequest(ctx context) RequestData {

  x:=ctx.Value(key)

  if x!=nil {

     return x.(RequestData)

  }

  return RequestData{}

}

當(dāng)然,如果要更改RequestData,則需要添加指向上下文的指針。


查看完整回答
反對 回復(fù) 2022-04-20
?
偶然的你

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

這就是我現(xiàn)在在我的應(yīng)用程序中使用的。我使用簡單的 settters 和 getter 從上下文中檢索值。


import (

    "context"

    "github.com/google/uuid"

)


const userIdContextKey = "user_id" // type is uuid


func addUserIdToContext(ctx context.Context, user uuid.UUID) context.Context {

    return context.WithValue(ctx, UserIdContextKey, user)

}


func userIDFromContext(ctx context.Context) uuid.UUID {

    return ctx.Value(UserIdContextKey).(uuid.UUID)

}

然后在一個(gè)中間件中,我已經(jīng)檢索了 userId,我通過將上下文和用戶 ID 傳遞給addUserIdToContext()函數(shù)來將值添加到上下文中。


ctx := addUserIdToContext(r.Context(), userId)

當(dāng)我想從上下文中檢索用戶時(shí),我只需要調(diào)用userIDFromContext(ctx)并將請求上下文傳遞給它。


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

    createdBy := userIDFromContext(r.Context())

    // do something with createdBy

}

我知道這不是最優(yōu)雅甚至類型安全的解決方案,但是,嘿,因?yàn)槲艺趪L試構(gòu)建它,它工作得很好。


查看完整回答
反對 回復(fù) 2022-04-20
  • 2 回答
  • 0 關(guān)注
  • 128 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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