在控制器上切换类型

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

Type switch on controller

问题

我正在使用revel实现一个简单的拦截器,其唯一责任是确保用户已经通过身份验证,如果没有则重定向到身份验证页面。我有以下代码:

func setUser(c *revel.Controller) revel.Result {
    switch interface{}(c.Type).(type) {
    case controllers.Auth:
        return nil
    }
    return c.Redirect(controllers.Auth.Index)
}

controllers.Auth 类型的 case 永远不会被执行,导致无限循环。我猜测可能有一些明显的问题我忽略了,但在我弄清楚如何通过gdb运行revel应用程序进行调试之前,我想在这里询问一下。

英文:

I'm implementing a simple interceptor using revel, who's sole responsibility is to ensure that a user is authenticated and redirect to auth page if not. I have something to the effect of

func setUser(c *revel.Controller) revel.Result {
    switch interface{}(c.Type).(type) {
    case controllers.Auth:
        return nil
    }
    return c.Redirect(controllers.Auth.Index)
}

The type case controllers.Auth is never encountered, effectively resulting in an infinite loop. I'm assuming there's something obvious I'm missing, but while I figure out how to run a revel app through gdb to try and debug this, figured I'd ask here.

答案1

得分: 2

我相信对于你的开关语句,你需要一个基本情况。你无限地进入其中,因为c的类型不是controllers.Auth,而且你没有其他情况。但是,在你的用例中,没有理由使用开关语句,我个人也不会这样做。它是二进制的,所以只需在controllers.Auth上进行类型断言,如果不是那样,就进行重定向。

func setUser(c *revel.Controller) revel.Result {
    if _, ok := c.(controllers.Auth); ok {
        return c.Redirect(controllers.Auth.Index)   
    }
    return nil
}
英文:

I believe for your switch you need a base case. You end up in it infinitely because c's type is not controllers.Auth and you have no other cases. But, in your use case, there is no reason to use a switch and I personally wouldn't. It's binary, so just type assert on controllers.Auth, if it's not that then you redirect.

func setUser(c *revel.Controller) revel.Result {
    if _, ok := c.(controllers.Auth); ok {
             return c.Redirect(controllers.Auth.Index)   
    }
    return nil
}

huangapple
  • 本文由 发表于 2016年1月19日 04:46:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/34863775.html
匿名

发表评论

匿名网友

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

确定