简体   繁体   English

控制器上的类型开关

[英]Type switch on controller

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. 我正在使用revel实现一个简单的拦截器,他的唯一职责是确保对用户进行身份验证,如果没有,则重定向到身份验证页面。 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. 从来没有遇到过case controllers.Auth类型,有效地导致了无限循环。 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. 我以为我很想念一些东西,但是当我弄清楚如何通过gdb运行一个revel应用程序来尝试调试它时,我想在这里问。

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. 由于c的类型不是controllers.Auth并且没有其他情况,因此您可能会无限期地使用它。 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. 它是二进制文件,因此只需在controllers.Auth上键入assert即可,如果不是,则可以重定向。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM