如何从gofiber的本地上下文中提取值

huangapple go评论66阅读模式
英文:

How to extract values from local context in gofiber

问题

我已经成功使用本地上下文和自定义中间件设置数据库查询结果。我正在尝试查看如何对用户进行身份验证,然后从数据库中获取他们的详细信息并将其注入到上下文中。这已经完成了。

在路由的最终方法中,本地数据实际上是一个接口,我想从先前的身份验证中间件设置的数据中提取字段。我该如何处理这个接口类型,以便将其转换为类似结构体或 JSON 的形式,以便获取字段和值以进行一些逻辑处理?

user := c.Locals("user")
fmt.Println("checking for locals", user)
从上面的代码中可以看出,user 是一个名为 user 的结构体。

{
Name string json:"name"
Email string json:"email"
ID string json:"id"
Password string json:"password"
}
我该如何获取姓名和电子邮件?

英文:

I have managed to use the local context to set database query results using a custom middleware. I am trying to see how I can authenticate a user then pull their details from the database and inject it to the context. This has been done.

The local data on the final method on the route is actually an interface and I would like to extract fields from the data I set from the previous auth middleware. How can I work with this interface type to some form like a struct or json so that I can get the fields and values for doing some logic?

user := c.Locals("user") 
fmt.Println("checking for locals",user)

From above user is of struct user

 {
Name string `json:"name"`
Emain string `json:"email"`
ID string `json:"id"`
Password string `json:"password"`
}

How can I get the name and email ?

答案1

得分: 4

所以在研究了Fiber文档并阅读了关于接口和空接口的内容后,我认为我有一个解决方案,但可能需要更正。

我看到可以将接口转换为具体类型。在我的情况下,我会取类型为var user interface{}c.Locals("user"),然后将其转换为一个结构体,将用户模型的指针传递给它,如下所示:

user := c.Locals("user")
details, ok := user.(*models.User)
fmt.Println("checking for locals -----------", details.Name)
英文:

So after digging into the fiber docs and reading about interfaces and especially empty interfaces I think I have a solution but stand to be corrected

I saw one can cast an interface to a concrete type. In my case I would take the c.Locals("user") of type var user interface{}

then cast it to a struct passing the pointer to the user model as follows

user := c.Locals("user") 
 details, ok :=user.(*models.User)
 fmt.Println("checking for locals -----------",details.Name)

huangapple
  • 本文由 发表于 2021年10月14日 03:08:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/69561058.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定