urlsmap.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package types
  15. import (
  16. "fmt"
  17. "sort"
  18. "strings"
  19. )
  20. type URLsMap map[string]URLs
  21. // NewURLsMap returns a URLsMap instantiated from the given string,
  22. // which consists of discovery-formatted names-to-URLs, like:
  23. // mach0=http://1.1.1.1:2380,mach0=http://2.2.2.2::2380,mach1=http://3.3.3.3:2380,mach2=http://4.4.4.4:2380
  24. func NewURLsMap(s string) (URLsMap, error) {
  25. m := parse(s)
  26. cl := URLsMap{}
  27. for name, urls := range m {
  28. us, err := NewURLs(urls)
  29. if err != nil {
  30. return nil, err
  31. }
  32. cl[name] = us
  33. }
  34. return cl, nil
  35. }
  36. // String returns NameURLPairs into discovery-formatted name-to-URLs sorted by name.
  37. func (c URLsMap) String() string {
  38. pairs := make([]string, 0)
  39. for name, urls := range c {
  40. for _, url := range urls {
  41. pairs = append(pairs, fmt.Sprintf("%s=%s", name, url.String()))
  42. }
  43. }
  44. sort.Strings(pairs)
  45. return strings.Join(pairs, ",")
  46. }
  47. // URLs returns a list of all URLs.
  48. // The returned list is sorted in ascending lexicographical order.
  49. func (c URLsMap) URLs() []string {
  50. urls := make([]string, 0)
  51. for _, us := range c {
  52. for _, u := range us {
  53. urls = append(urls, u.String())
  54. }
  55. }
  56. sort.Strings(urls)
  57. return urls
  58. }
  59. func (c URLsMap) Len() int {
  60. return len(c)
  61. }
  62. // parse parses the given string and returns a map listing the values specified for each key.
  63. func parse(s string) map[string][]string {
  64. m := make(map[string][]string)
  65. for s != "" {
  66. key := s
  67. if i := strings.IndexAny(key, ","); i >= 0 {
  68. key, s = key[:i], key[i+1:]
  69. } else {
  70. s = ""
  71. }
  72. if key == "" {
  73. continue
  74. }
  75. value := ""
  76. if i := strings.Index(key, "="); i >= 0 {
  77. key, value = key[:i], key[i+1:]
  78. }
  79. m[key] = append(m[key], value)
  80. }
  81. return m
  82. }