geoip.go 628 B

123456789101112131415161718192021222324252627282930313233343536
  1. package config
  2. import (
  3. "errors"
  4. "fmt"
  5. "regexp"
  6. "strings"
  7. )
  8. var (
  9. countryCodeRegexp = regexp.MustCompile(`^[a-zA-Z]{2}$`)
  10. ErrNotCountryCode = errors.New("config.Bot: invalid country code")
  11. )
  12. type GeoIP struct {
  13. Countries []string `json:"countries"`
  14. }
  15. func (g *GeoIP) Valid() error {
  16. var errs []error
  17. for i, cc := range g.Countries {
  18. if !countryCodeRegexp.MatchString(cc) {
  19. errs = append(errs, fmt.Errorf("%w: %s", ErrNotCountryCode, cc))
  20. }
  21. g.Countries[i] = strings.ToLower(cc)
  22. }
  23. if len(errs) != 0 {
  24. return fmt.Errorf("bot.GeoIP: invalid GeoIP settings: %w", errors.Join(errs...))
  25. }
  26. return nil
  27. }