登录
首页 >  Golang >  Go问答

请求的上下文中包含自定义类型字段

来源:stackoverflow

时间:2024-02-23 10:27:26 134浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《请求的上下文中包含自定义类型字段》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在使用 go 编写一个或多或少简单的 web 应用程序,它提供了一个 rest api。当请求传入时,我想将用户的 id(作为 api 令牌的一部分)临时存储在请求上下文中。在阅读了一些文章和文档后,我仍然很困惑如何确保使用 context.withvalue() 附加到上下文的值可以在没有类型断言的情况下使用,而是使用某种结构。

这是我到目前为止所想到的:

// 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() 函数,或者是否有替代的类似方法。


解决方案


要使用您构建的内容,您必须使用类型断言:

rctx:=request.context().(requestcontext)

如果您有一个以与您相同的方式包装上下文的中间件,这将会中断。

另一种方法是使用基本上下文,并添加带有私钥的助手来访问值:

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{}
}

当然,如果你想改变requestdata,你需要添加一个指向上下文的指针。

到这里,我们也就讲完了《请求的上下文中包含自定义类型字段》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>