entry.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package discovery
  2. import "net"
  3. // NewEntry creates a new entry.
  4. func NewEntry(url string) (*Entry, error) {
  5. host, port, err := net.SplitHostPort(url)
  6. if err != nil {
  7. return nil, err
  8. }
  9. return &Entry{host, port}, nil
  10. }
  11. // An Entry represents a host.
  12. type Entry struct {
  13. Host string
  14. Port string
  15. }
  16. // Equals returns true if cmp contains the same data.
  17. func (e *Entry) Equals(cmp *Entry) bool {
  18. return e.Host == cmp.Host && e.Port == cmp.Port
  19. }
  20. // String returns the string form of an entry.
  21. func (e *Entry) String() string {
  22. return net.JoinHostPort(e.Host, e.Port)
  23. }
  24. // Entries is a list of *Entry with some helpers.
  25. type Entries []*Entry
  26. // Equals returns true if cmp contains the same data.
  27. func (e Entries) Equals(cmp Entries) bool {
  28. // Check if the file has really changed.
  29. if len(e) != len(cmp) {
  30. return false
  31. }
  32. for i := range e {
  33. if !e[i].Equals(cmp[i]) {
  34. return false
  35. }
  36. }
  37. return true
  38. }
  39. // Contains returns true if the Entries contain a given Entry.
  40. func (e Entries) Contains(entry *Entry) bool {
  41. for _, curr := range e {
  42. if curr.Equals(entry) {
  43. return true
  44. }
  45. }
  46. return false
  47. }
  48. // Diff compares two entries and returns the added and removed entries.
  49. func (e Entries) Diff(cmp Entries) (Entries, Entries) {
  50. added := Entries{}
  51. for _, entry := range cmp {
  52. if !e.Contains(entry) {
  53. added = append(added, entry)
  54. }
  55. }
  56. removed := Entries{}
  57. for _, entry := range e {
  58. if !cmp.Contains(entry) {
  59. removed = append(removed, entry)
  60. }
  61. }
  62. return added, removed
  63. }
  64. // CreateEntries returns an array of entries based on the given addresses.
  65. func CreateEntries(addrs []string) (Entries, error) {
  66. entries := Entries{}
  67. if addrs == nil {
  68. return entries, nil
  69. }
  70. for _, addr := range addrs {
  71. if len(addr) == 0 {
  72. continue
  73. }
  74. entry, err := NewEntry(addr)
  75. if err != nil {
  76. return nil, err
  77. }
  78. entries = append(entries, entry)
  79. }
  80. return entries, nil
  81. }