validator.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. ip := net.ParseIP(input.IP)
  15. if ip == nil || ip.To4() == nil {
  16. resp.Errors = append(resp.Errors, "IP 地址格式不正确。")
  17. }
  18. if input.Prefix < 0 || input.Prefix > 32 {
  19. resp.Errors = append(resp.Errors, "前缀长度不正确。")
  20. }
  21. if input.Gateway != "" {
  22. gateway := net.ParseIP(input.Gateway)
  23. if gateway == nil || gateway.To4() == nil {
  24. resp.Errors = append(resp.Errors, "网关格式不正确。")
  25. } else if ip != nil && ip.To4() != nil && input.Prefix >= 0 && input.Prefix <= 32 {
  26. mask := net.CIDRMask(input.Prefix, 32)
  27. ipNet := &net.IPNet{IP: ip.Mask(mask), Mask: mask}
  28. if !ipNet.Contains(gateway) {
  29. resp.Errors = append(resp.Errors, "网关与目标接口 IP 不在同一子网。")
  30. }
  31. }
  32. }
  33. for _, dns := range input.DNS {
  34. if dns == "" {
  35. continue
  36. }
  37. parsed := net.ParseIP(dns)
  38. if parsed == nil || parsed.To4() == nil {
  39. resp.Errors = append(resp.Errors, fmt.Sprintf("DNS 格式不正确:%s", dns))
  40. }
  41. }
  42. if ip != nil && ip.To4() != nil {
  43. if ip[0] == 169 && ip[1] == 254 {
  44. resp.Warnings = append(resp.Warnings, "目标接口使用的是链路本地地址,通常仅适合同链路通信。")
  45. }
  46. }
  47. resp.Valid = len(resp.Errors) == 0
  48. return resp
  49. }