mirror of
1
Fork 0
gotosocial/internal/validate/structvalidation.go

75 lines
1.8 KiB
Go
Raw Normal View History

/*
GoToSocial
Copyright (C) 2021 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-31 15:59:12 +02:00
// Validation Panic messages
const (
2021-09-01 18:29:25 +02:00
InvalidPanic = "validate function was passed invalid item"
)
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 10:30:40 +02:00
switch reflect.TypeOf(s).Kind() {
case reflect.Invalid:
2021-09-01 18:29:25 +02:00
panic(InvalidPanic)
}
err := v.Struct(s)
return processValidationError(err)
}
func processValidationError(err error) error {
if err == nil {
return nil
}
if ive, ok := err.(*validator.InvalidValidationError); ok {
panic(ive)
}
return err.(validator.ValidationErrors)
}