将echo.Context转换为context.Context

use*_*647 -1 go graphql

我正在编写一个Web应用程序,使用Go作为后端.我正在使用这个GraphQL库(链接)和Echo Web框架(链接).问题是graphql-go库使用contextGo中的包,同时Echo使用自己的自定义上下文,并删除了对标准context包的支持.

我的问题是,有没有办法使用context.Context作为echo.Context,在下面的例子中?

api.go
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}))
}
Run Code Online (Sandbox Code Playgroud)

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
    ...
}
Run Code Online (Sandbox Code Playgroud)

我如何使我的graphql解析器可以使用echo上下文.非常感谢,任何帮助表示赞赏.

hob*_*bbs 9

echo.Context不能用作 context.Context,但它确实引用了一个; 如果c是echo上下文则c.Request().Context()context.Context传入请求,例如,如果用户关闭连接,则将取消该请求.

如果需要,您可以通过Get一方面使用方法而另一方面使用方法将其他有用的值从echo上下文复制到stdlib上下文WithValue.如果您总是希望复制某些值,则可以编写辅助函数来执行此操作.