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