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 elasticsearch
  • ¥30 python ttk 获取下拉框问题
  • ¥15 uniapp的uni-datetime-picker组件在ios端不适配
  • ¥15 前端 uniapp App端在离线状态如何使用modbus 连接手机蓝牙进行读写操控机器?
  • ¥15 SQL语句根据字段自动生成行
  • ¥500 “掌声响起来”软件(不确定性人工智能)
  • ¥500 我要找大模型一体机产品手册和应用案例
  • ¥20 关于游戏c++语言代码问题
  • ¥15 如何制作永久二维码,最好是微信也可以扫开的。(相关搜索:管理系统)
  • ¥15 delphi indy cookie 有效期