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