将 echo.Context 转换为 context.Context [英] Transforming echo.Context to context.Context
问题描述
我正在编写一个 Web 应用程序,使用 Go 作为后端.我正在使用这个 GraphQL 库 (link) 和 Echo web 框架 (链接).问题在于 graphql-go
库使用 Go 中的 context
包,而 Echo
使用自己的自定义上下文,并删除了对标准的 context
包.
I am writing a web application, using Go as the backend. I'm using this GraphQL library (link), and the Echo web framework (link). The problem is that that the graphql-go
library uses the context
package in Go, while Echo
uses its own custom context, and removed support for the standard context
package.
我的问题是,在下面的示例中,有没有办法将 context.Context 用作 echo.Context?
My question would be, is there a way to use context.Context as echo.Context, in the following example?
func (api *API) Bind(group *echo.Group) {
group.Use(middleware.JWTWithConfig(middleware.JWTConfig{
SigningKey: []byte("SOME_REAL_SECRET_KEY"),
SigningMethod: "HS256",
}))
group.GET("/graphql", api.GraphQLHandler)
group.POST("/query", echo.WrapHandler(&relay.Handler{Schema: schema}))
}
graphql.go
func (r *Resolver) Viewer(ctx context.Context, arg *struct{ Token *string }) (*viewerResolver, error) {
token := ctx.Value("user").(*jwt.Token) // oops on this line, graphql-go uses context.Context, but the echo middleware provides echo.Context
...
}
我如何让我的 graphql 解析器可以使用回声上下文.非常感谢,感谢您的帮助.
How would I make the echo context available to my graphql resolvers. Thank you very much, any help is appreciated.
推荐答案
一个 echo.Context 不能用作一个 context.Context,但它引用 一;如果 c
是回声上下文,则 c.Request().Context()
是传入请求的 context.Context
,这将是例如,如果用户关闭连接,则取消.
An echo.Context can't be used as a context.Context, but it does refer to one; if c
is the echo context then c.Request().Context()
is the context.Context
for the incoming request, which will be canceled if the user closes the connection, for instance.
如果需要,您可以将其他有用的值从 echo 上下文复制到 stdlib 上下文,一方面使用 Get
方法,另一方面使用 WithValue
方法.其他.如果您总是想复制一些值,那么您可以编写一个辅助函数来这样做.
You can copy other useful values from the echo context to the stdlib context, if needed, by using the Get
method on the one hand and the WithValue
method on the other. If there are some values that you always want copied, then you can write a helper function to do so.
这篇关于将 echo.Context 转换为 context.Context的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!