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 16:29:25 +00:00
package validate
import (
"reflect"
"github.com/go-playground/validator/v10"
2021-09-01 16:29:25 +00:00
"github.com/superseriousbusiness/gotosocial/internal/regexes"
)
var v *validator.Validate
2021-08-31 13:59:12 +00:00
// Validation Panic messages
const (
2021-09-01 16:29:25 +00:00
InvalidPanic = "validate function was passed invalid item"
)
2021-08-30 18:20:27 +00:00
func ulidValidator(fl validator.FieldLevel) bool {
field := fl.Field()
2021-08-30 18:20:27 +00:00
switch field.Kind() {
case reflect.String:
2021-09-01 16:29:25 +00:00
return regexes.ULID.MatchString(field.String())
2021-08-30 18:20:27 +00:00
default:
return false
}
}
func init() {
v = validator.New()
2021-09-02 10:24:18 +00:00
if err := v.RegisterValidation("ulid", ulidValidator); err != nil {
panic(err)
}
}
2021-09-01 16:29:25 +00:00
// Struct validates the passed struct, returning validator.ValidationErrors if invalid, or nil if OK.
func Struct(s interface{}) error {
2021-09-03 08:30:40 +00:00
switch reflect.TypeOf(s).Kind() {
case reflect.Invalid:
2021-09-01 16:29:25 +00: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)
}