百万级并发IM即时消息系统(5)校验器govalidator

govalidator package - github.com/asaskevich/govalidator - Go Packages

1.govalidator校验

提供了对一些类型的检验方法,只需要在结构体定义时加对应的tag即可,随后可调用检验方法去检验

2.结构体定义设置校验格式

type UserBasic struct {
	gorm.Model    //告诉数据库这个结构体映射一张表,同时数据库操作需要更新里面的几个时间戳
	Name          string
	PassWord      string
	Phone         string `valid:"matches(^1[3-9]{1}\\d{9}$)"` //正则表达式用于校验号码
	Email         string `valid:"email"`                      //校验邮箱格式
	Avatar        string //头像
	Identity      string
	ClientIp      string
	ClientPort    string
	Salt          string
	LoginTime     time.Time
	HeartbeatTime time.Time
	LoginOutTime  time.Time `gorm:"column:login_out_time" json:"login_out_time"`
	IsLogout      bool
	DeviceInfo    string
}

3.service层选择校验当前变量是否符合格式

_, err := govalidator.ValidateStruct(user) //用govalidator校验这个结构体字段格式
	if err != nil {
		fmt.Println(err)
		c.JSON(200, gin.H{
			"code":    -1, //  0成功   -1失败
			"message": "修改参数不匹配!",
			"data":    user,
		})
	} else {
		models.UpdateUser(user)
		c.JSON(200, gin.H{
			"code":    0, //  0成功   -1失败
			"message": "修改用户成功!",
			"data":    user,
		})
	}

猜你喜欢

转载自blog.csdn.net/m0_50973548/article/details/132653102