validator.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package validator
  2. import (
  3. "fmt"
  4. "net"
  5. "quickip/internal/model"
  6. )
  7. type Service struct{}
  8. func New() *Service { return &Service{} }
  9. func (s *Service) Validate(input model.InterfaceConfig) model.ValidateResponse {
  10. resp := model.ValidateResponse{Valid: false, Warnings: []string{}, Errors: []string{}}
  11. if input.Interface == "" {
  12. resp.Errors = append(resp.Errors, "目标接口不能为空。")
  13. }
  14. if input.Dhcp4 {
  15. resp.Valid = len(resp.Errors) == 0
  16. return resp
  17. }
  18. ip := net.ParseIP(input.IP)
  19. if ip == nil || ip.To4() == nil {
  20. resp.Errors = append(resp.Errors, "IP 地址格式不正确。")
  21. }
  22. if input.Prefix < 0 || input.Prefix > 32 {
  23. resp.Errors = append(resp.Errors, "前缀长度不正确。")
  24. }
  25. if input.Gateway != "" {
  26. gateway := net.ParseIP(input.Gateway)
  27. if gateway == nil || gateway.To4() == nil {
  28. resp.Errors = append(resp.Errors, "网关格式不正确。")
  29. } else if ip != nil && ip.To4() != nil && input.Prefix >= 0 && input.Prefix <= 32 {
  30. mask := net.CIDRMask(input.Prefix, 32)
  31. ipNet := &net.IPNet{IP: ip.Mask(mask), Mask: mask}
  32. if !ipNet.Contains(gateway) {
  33. resp.Errors = append(resp.Errors, "网关与目标接口 IP 不在同一子网。")
  34. }
  35. }
  36. }
  37. for _, dns := range input.DNS {
  38. if dns == "" {
  39. continue
  40. }
  41. parsed := net.ParseIP(dns)
  42. if parsed == nil || parsed.To4() == nil {
  43. resp.Errors = append(resp.Errors, fmt.Sprintf("DNS 格式不正确:%s", dns))
  44. }
  45. }
  46. if ip != nil && ip.To4() != nil {
  47. if ip[0] == 169 && ip[1] == 254 {
  48. resp.Warnings = append(resp.Warnings, "目标接口使用的是链路本地地址,通常仅适合同链路通信。")
  49. }
  50. }
  51. resp.Valid = len(resp.Errors) == 0
  52. return resp
  53. }