douhuai4155 2018-02-02 06:29
浏览 18
已采纳

如何使用保存在控制器中访问的中间件中的上下文中的“类型结构”

This is my first question regarding GoLang please be gentle. I am building a test JSON API.

I have a type struct named User

type User struct {
    UserID              int
    Email               string
    FirstName           string
    LastName            string
    PasswordHash        string
}

In middleware, I verify JWT token is valid and if so, I load entire record of User and save it in the context so that it is available in handlers under.

So in middleware, I save User struct like this

    context.Set(r, "User",  *User)
    fmt.Println(*User)

    next.ServeHTTP(w, r)

Output of Println is

{12 sallu@domain.com.au Mr. Sallu $2a$14oUg3d1rm./.B/vUyhYR9/hlHfagE4tGicNc14EWK3u }

Then in the final handler I access this context and get User object.

User    := context.Get(r, "User")

fmt.Println("---User---", fmt.Sprintf(" %T ", User))
fmt.Println(User)

Output of Println is

---User---  models.User
{12 sallu@domain.com.au Mr. Sallu $2a$14oUg3d1rm./.B/vUyhYR9/hlHfagE4tGicNc14EWK3u }

The issue is that in Controller when I access User.Email I am getting an error

User.Email undefined (type interface {} is interface with no methods)

How can I fix this..? I want to use User.Email or User.UserID. Seems like context is doing something to it.

Please help

  • 写回答

2条回答 默认 最新

  • doupingdiao3546 2018-02-02 06:55
    关注

    Everywhere in your code please use different names for variable and type.

    e.g. keep type User and variable user.

    In your controller, type assert your user back to User.

    if u, ok := user.(User); ok {
        fmt.Println(u.Email)
    }
    

    https://tour.golang.org/methods/15

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!