host.go 727 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package json
  2. import (
  3. "encoding/json"
  4. "net"
  5. )
  6. type Host struct {
  7. domain string
  8. ip net.IP
  9. }
  10. func NewIPHost(ip net.IP) *Host {
  11. return &Host{
  12. ip: ip,
  13. }
  14. }
  15. func NewDomainHost(domain string) *Host {
  16. return &Host{
  17. domain: domain,
  18. }
  19. }
  20. func (this *Host) UnmarshalJSON(data []byte) error {
  21. var rawStr string
  22. if err := json.Unmarshal(data, &rawStr); err != nil {
  23. return err
  24. }
  25. ip := net.ParseIP(rawStr)
  26. if ip != nil {
  27. this.ip = ip
  28. } else {
  29. this.domain = rawStr
  30. }
  31. return nil
  32. }
  33. func (this *Host) IsIP() bool {
  34. return this.ip != nil
  35. }
  36. func (this *Host) IsDomain() bool {
  37. return !this.IsIP()
  38. }
  39. func (this *Host) IP() net.IP {
  40. return this.ip
  41. }
  42. func (this *Host) Domain() string {
  43. return this.domain
  44. }