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