许多带验证的golang框架,如何编写结构验证和使用sql
的方法示例1:
//create struct register form
type UserRegister struct {
Email string `validate:"required,max=20,min=8"`
Password string `validate:"required,max=20,min=8"`
Captcha string `validate:"required,captcha"`
}
//method Insert for UserRegister struct if validation success
func (u *UserRegister) Insert() {
//insert code
}
//validate -> insert
func Controller(n *N) {
var userRegister UserRegister
err := validator.Validate(&userRegister)
if err == nil {
userRegister.Insert()
}
}
示例2:
//Main struct User
type User struct {
Id int
Email string
Password string
Active int
//another fields from user table
}
//methods for work with User: user.Insert(), user.SelectById() etc.
func (u *UserRegister) Insert() {
//insert code
}
func (u *UserRegister) IsUniqueEmail() {
//check unique code
}
//struct for validation register form
type UserRegister struct {
Email string `validate:"required,max=20,min=8"`
Password string `validate:"required,max=20,min=8"`
Captcha string `validate:"required,captcha"`
}
//validate userRegister if succeess -> transfer data to main user struct -> insert
func Controller(n *N) {
var userLogin UserRegister
err := validator.Validate(&userRegister)
if err == nil {
//transfer data from userRegister to user
user := User{
Email: userRegister.Email,
Password: userRegister.Password,
...
}
//insert
user.Insert()
}
}
关于示例1:我们使用验证和数据库方法创建struct。有时我需要在不同的结构中使用相同的方法,因此每次都需要复制这些方法。
关于示例2:我们使用数据库方法和其他结构创建主结构以进行验证。我不能使用struct User
,其字段Password和PasswordRepeat在控制器登录和寄存器中有验证required
因为验证将失败登录cuz struct需要PasswordRepeat。
组织代码的最佳方法是什么?