-
Notifications
You must be signed in to change notification settings - Fork 0
HW09 is completed #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
hw09_struct_validator/validator.go
Outdated
|
|
||
| func (v ValidationErrors) Error() string { | ||
| panic("implement me") | ||
| var result string |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Для сборки строк лучше использовать strings.Builder это более оптимальный по памяти способ. Пример:
var b strings.Builder
for i := 0; i < 10; i++ {
b.WriteString("foo")
}
return b.String()
По ссылке есть ещё пример использования, который подойдёт к вашей ситуации.
| go 1.16 | ||
|
|
||
| require ( | ||
| github.com/fatih/structs v1.1.0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Обратите внимание, что данный репозиторий заархивирован и более не поддерживается. Таких зависимостей лучше избегать или быть готовыми их поддерживать своими силами.
hw09_struct_validator/validator.go
Outdated
| return nil | ||
| } | ||
|
|
||
| return errors.New(result.Error()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно просто вернуть result так, как он у нас реализует интерфейс error. Это так же позволит нам избавится от проверки if len(result) == 0
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если я возвращаю просто result, то не срабатывает мой метод Error
expected: *errors.errorString(&errors.errorString{s:"Validation error for field "Email": Value should match regexp "^\\w+@\\w+\\.\\w+$". Value "1gmail.com" is not match\n"})
actual : hw09structvalidator.ValidationErrors(hw09structvalidator.ValidationErrors{hw09structvalidator.ValidationError{Field:"Email", Err:(*errors.errorString)(0xc000298070)}})
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, всё верно. Вы сравниваете два разных типа, они никогда не будут одинаковыми. Вы можете либо сравнивать строковое представление ошибки используя assert.EqalError, либо вместо errors.New в тестах конструировать ValidationErrors
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Я в тестах сравниваю только тексты ошибок. Но проверку на длину и возврат nil я оставила, так как в противном случае вместо nil в result было hw09structvalidator.ValidationErrors(nil)
hw09_struct_validator/validator.go
Outdated
|
|
||
| type ValidationErrors []ValidationError | ||
|
|
||
| type ValidatorType int |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Намного более удобно когда у нас объявлен типа ValidationErrors и сразу после этого идут методы этого типа, в нашем случае func (v ValidationErrors) Error() string.
hw09_struct_validator/validator.go
Outdated
|
|
||
| delimiterPos := strings.Index(str, ":") | ||
| if delimiterPos == -1 { | ||
| panic("Incorrect validator definition. Semicolon should be present") |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Тут лучше вернуть ошибку: return errors.New("Incorrect validator definition. Semicolon should be present"). Старайтесь не использовать panic в коде, это затрудняет его поддержку. Замените все паники на ошибки.
hw09_struct_validator/validator.go
Outdated
|
|
||
| const VALIDATE_TAG_NAME = "validate" | ||
|
|
||
| var NilValidationError = ValidationError{"", nil} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Немного не точно. Это не nil ошибка, а пустая ошибка. Это немного разные вещи.
|
|
||
| type ValidatorType int | ||
|
|
||
| const ( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это очень круто, что вы создали тип под возможные типы валидаторов и добавили для них константы. Только тут будет более удобно использовать не числовые константы а строки. Это позволит нам избавится от getValidatorTypeByString.
hw09_struct_validator/validator.go
Outdated
| } | ||
| } | ||
|
|
||
| func getValidatorValueByString(ruleString string) ValidatorValue { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше будет просто привести тип в коде. Не принято создавать отдельный функций для этого.
|
|
||
| // Place your code here. | ||
| Validate(tt.in) | ||
| _ = tt |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Можно удалить строчку _ = tt.
| stT := reflect.TypeOf(v) | ||
| stV := reflect.ValueOf(v) | ||
|
|
||
| for i:=0; i<stT.NumField(); i++ { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Перед тем как вызвать NumField нужно убедится что v это структура иначе мы получим панику.
Домашнее задание №9 «Валидатор структур»
Чек-лист студента (Что это?)
go mod tidy..syncфайл. Зачем его удалять?Критерии оценки
Зачёт от 7 баллов