doupai6875 2016-10-31 18:51
浏览 151
已采纳

从Golang中的接口创建类型的变量

I am trying to create validator/binder middleware in go using gin framework.

This is the model

type LoginForm struct{
    Email string `json:"email" form:"email" binding:"email,required"`
    Password string `json:"password" form:"password" binding:"required"`
}

Router

router.POST("/login",middlewares.Validator(LoginForm{}) ,controllers.Login)

Middleware

func Validator(v interface{}) gin.HandlerFunc{
    return func(c *gin.Context){
        a := reflect.New(reflect.TypeOf(v))
        err:=c.Bind(&a)
        if(err!=nil){
            respondWithError(401, "Login Error", c)
            return
        }
        c.Set("LoginForm",a)
        c.Next()
    }
}

I am very new to golang. I understand the problem is with the binding to the wrong variable. Is there any other way of solving this?

  • 写回答

1条回答 默认 最新

  • drpzr64329 2016-10-31 19:37
    关注

    Clarify my comment,

    Instead of having the signature func Validator(v interface{}) gin.HandlerFunc for the MW, use func Validator(f Viewfactory) gin.HandlerFunc

    Where ViewFactory if a function type such as type ViewFactory func() interface{}

    the MW can be changed so

    type ViewFactory func() interface{}
    
    func Validator(f ViewFactory) gin.HandlerFunc{
        return func(c *gin.Context){
            a := f()
            err:=c.Bind(a) // I don t think you need to send by ref here, to check by yourself
            if(err!=nil){
                respondWithError(401, "Login Error", c)
                return
            }
            c.Set("LoginForm",a)
            c.Next()
        }
    }
    

    You can write the router like this

    type LoginForm struct{
        Email string `json:"email" form:"email" binding:"email,required"`
        Password string `json:"password" form:"password" binding:"required"`
    }
    func NewLoginForm() interface{} {
       return &LoginForm{}
    }
    router.POST("/login",middlewares.Validator(NewLoginForm) ,controllers.Login)
    

    Going further, i think you may have to find out about this later, once you have an interface{} value, you can make it back a LoginForm like this v := some.(*LoginForm).

    Or like this for more security

    if v, ok := some.(*LoginForm); ok {
     // v is a *LoginForm
    }
    

    See golang type assertions for more in depth information.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里