2024-01-04 17:55:26 +00:00
|
|
|
// Package validate provides a wrapper around the go-playground/validator package
|
2022-10-30 04:05:38 +00:00
|
|
|
package validate
|
|
|
|
|
2023-03-07 06:18:58 +00:00
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
|
|
)
|
2022-10-30 04:05:38 +00:00
|
|
|
|
|
|
|
var validate *validator.Validate
|
|
|
|
|
2024-01-04 17:55:26 +00:00
|
|
|
func init() { // nolint
|
2022-10-30 04:05:38 +00:00
|
|
|
validate = validator.New()
|
2023-03-07 06:18:58 +00:00
|
|
|
|
|
|
|
err := validate.RegisterValidation("shoutrrr", func(fl validator.FieldLevel) bool {
|
|
|
|
prefixes := [...]string{
|
2023-11-16 02:53:06 +00:00
|
|
|
"bark://",
|
2023-03-07 06:18:58 +00:00
|
|
|
"discord://",
|
|
|
|
"smtp://",
|
|
|
|
"gotify://",
|
|
|
|
"googlechat://",
|
|
|
|
"ifttt://",
|
|
|
|
"join://",
|
|
|
|
"mattermost://",
|
|
|
|
"matrix://",
|
2023-11-16 02:53:06 +00:00
|
|
|
"ntfy://",
|
2023-03-07 06:18:58 +00:00
|
|
|
"opsgenie://",
|
|
|
|
"pushbullet://",
|
|
|
|
"pushover://",
|
|
|
|
"rocketchat://",
|
|
|
|
"slack://",
|
|
|
|
"teams://",
|
|
|
|
"telegram://",
|
|
|
|
"zulip://",
|
2023-04-16 19:21:33 +00:00
|
|
|
"generic://",
|
2023-11-16 02:53:06 +00:00
|
|
|
"generic+",
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
str := fl.Field().String()
|
|
|
|
if str == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, prefix := range prefixes {
|
|
|
|
if strings.HasPrefix(str, prefix) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2022-10-30 04:05:38 +00:00
|
|
|
}
|
|
|
|
|
2024-01-04 17:55:26 +00:00
|
|
|
// Check a struct for validation errors and returns any errors the occur. This
|
2022-10-30 04:05:38 +00:00
|
|
|
// wraps the validate.Struct() function and provides some error wrapping. When
|
|
|
|
// a validator.ValidationErrors is returned, it is wrapped transformed into a
|
|
|
|
// FieldErrors array and returned.
|
|
|
|
func Check(val any) error {
|
|
|
|
err := validate.Struct(val)
|
|
|
|
if err != nil {
|
2024-01-04 17:55:26 +00:00
|
|
|
verrors, ok := err.(validator.ValidationErrors) // nolint - we know it's a validator.ValidationErrors
|
2022-10-30 04:05:38 +00:00
|
|
|
if !ok {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
fields := make(FieldErrors, 0, len(verrors))
|
|
|
|
for _, verr := range verrors {
|
|
|
|
field := FieldError{
|
|
|
|
Field: verr.Field(),
|
|
|
|
Error: verr.Error(),
|
|
|
|
}
|
|
|
|
|
|
|
|
fields = append(fields, field)
|
|
|
|
}
|
|
|
|
return fields
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|