GoToSocial/internal/validate/structvalidation.go

69 lines
1.7 KiB
Go
Raw Normal View History

/*
GoToSocial
Copyright (C) 2021-2023 GoToSocial Authors admin@gotosocial.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
2021-09-01 18:29:25 +02:00
package validate
import (
"reflect"
"github.com/go-playground/validator/v10"
2021-09-01 18:29:25 +02:00
"github.com/superseriousbusiness/gotosocial/internal/regexes"
)
var v *validator.Validate
2021-08-30 20:20:27 +02:00
func ulidValidator(fl validator.FieldLevel) bool {
field := fl.Field()
2021-08-30 20:20:27 +02:00
switch field.Kind() {
case reflect.String:
2021-09-01 18:29:25 +02:00
return regexes.ULID.MatchString(field.String())
2021-08-30 20:20:27 +02:00
default:
return false
}
}
func init() {
v = validator.New()
2021-09-02 12:24:18 +02:00
if err := v.RegisterValidation("ulid", ulidValidator); err != nil {
panic(err)
}
}
2021-09-01 18:29:25 +02:00
// Struct validates the passed struct, returning validator.ValidationErrors if invalid, or nil if OK.
func Struct(s interface{}) error {
2021-09-03 11:12:19 +02:00
return processValidationError(v.Struct(s))
}
func processValidationError(err error) error {
if err == nil {
return nil
}
if ive, ok := err.(*validator.InvalidValidationError); ok {
panic(ive)
}
valErr, ok := err.(validator.ValidationErrors)
if !ok {
panic("*validator.InvalidValidationError could not be coerced to validator.ValidationErrors")
}
return valErr
}