将echo.Context转换为context.Context

问题描述 投票:-1回答:1

我正在编写一个Web应用程序,使用Go作为后端。我正在使用这个GraphQL库(link)和Echo web框架(link)。问题是graphql-go库在Go中使用context包,而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}))
}

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解析器可以使用echo上下文。非常感谢,任何帮助表示赞赏。

go graphql
1个回答
5
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.