B
B
bsbak2017-04-04 15:57:11
go
bsbak, 2017-04-04 15:57:11

How to properly organize structures with validation, methods?

Many golang frameworks have validation, so how do you write validation and sql queries?
Example 1:

//создаем структ регистрации формы
type UserRegister struct {
    Email    string    `validate:"required,max=20,min=8"`
    Password string `validate:"required,max=20,min=8"`
    Captcha  string `validate:"required,captcha"`
} 

//Создаем метод вставки в базу юзера
func (u *UserRegister) Insert() {
    //код вставки
}

//Проверяем вставляем
func Controller(n *N) {
    var userRegister UserRegister
    err := validator.Validate(&userRegister)
    if err == nil {
        userRegister.Insert()
    }
}

Example 2:
//Основной структ юзера
type User struct {
   Id       int
   Email    string
   Password string
   Active   int
   //еще какието столбцы таблицы юзера
}

//методы для работы с юзером user.Insert(), user.SelectById() и т.д.
func (u *UserRegister) Insert() {
    //код вставки
}
func (u *UserRegister) IsUniqueEmail() {
    //код проверки
}

//
type UserRegister struct {
    Email    string    `validate:"required,max=20,min=8"`
    Password string `validate:"required,max=20,min=8"`
    Captcha  string `validate:"required,captcha"`
}

//Валидация userRegister - переносим после валидации в основной struct юзер - вставляем
var userLogin UserRegister
err := validator.Validate(&userRegister)
if err == nil {
    //Переносим данные в основной юзер структ
    user := User{
        Email:       userRegister.Email,
        Password: userRegister.Password,
        ...
    }
    //Вставляем
    user.Insert()
}

That is, from example 1 - create a struct and methods for working with this struct OR from example 2 -
create the main user struct with methods, and other structures (userRegister for example) only for validation and after validation copy the data to the main struct for work with base! How is it correct (better, more convenient, why)? Maybe somehow differently?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ilya, 2017-04-04
@FireGM

Transferring data from structure to structure causes a bunch of allocations - minus performance.

B
bsbak, 2017-04-05
@bsbak

In general, the topic can be closed, I just don’t know how ... Here HERE I found links to ready-made projects, looked through the code and everything became clearer ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question