gotosocial/internal/validate/structvalidation.go

68 lines
1.8 KiB
Go
Raw Normal View History

// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// 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 17:29:25 +01:00
package validate
import (
"reflect"
"github.com/go-playground/validator/v10"
2021-09-01 17:29:25 +01:00
"github.com/superseriousbusiness/gotosocial/internal/regexes"
)
var v *validator.Validate
2021-08-30 19:20:27 +01:00
func ulidValidator(fl validator.FieldLevel) bool {
field := fl.Field()
2021-08-30 19:20:27 +01:00
switch field.Kind() {
case reflect.String:
2021-09-01 17:29:25 +01:00
return regexes.ULID.MatchString(field.String())
2021-08-30 19:20:27 +01:00
default:
return false
}
}
func init() {
v = validator.New()
2021-09-02 11:24:18 +01:00
if err := v.RegisterValidation("ulid", ulidValidator); err != nil {
panic(err)
}
}
2021-09-01 17:29:25 +01:00
// Struct validates the passed struct, returning validator.ValidationErrors if invalid, or nil if OK.
func Struct(s interface{}) error {
2021-09-03 10:12:19 +01: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
}