urlsmap.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. // URLsMap is a map from a name to its URLs.
  21. type URLsMap map[string]URLs
  22. // NewURLsMap returns a URLsMap instantiated from the given string,
  23. // which consists of discovery-formatted names-to-URLs, like:
  24. // 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
  25. func NewURLsMap(s string) (URLsMap, error) {
  26. m := parse(s)
  27. cl := URLsMap{}
  28. for name, urls := range m {
  29. us, err := NewURLs(urls)
  30. if err != nil {
  31. return nil, err
  32. }
  33. cl[name] = us
  34. }
  35. return cl, nil
  36. }
  37. // String turns URLsMap into discovery-formatted name-to-URLs sorted by name.
  38. func (c URLsMap) String() string {
  39. var pairs []string
  40. for name, urls := range c {
  41. for _, url := range urls {
  42. pairs = append(pairs, fmt.Sprintf("%s=%s", name, url.String()))
  43. }
  44. }
  45. sort.Strings(pairs)
  46. return strings.Join(pairs, ",")
  47. }
  48. // URLs returns a list of all URLs.
  49. // The returned list is sorted in ascending lexicographical order.
  50. func (c URLsMap) URLs() []string {
  51. var urls []string
  52. for _, us := range c {
  53. for _, u := range us {
  54. urls = append(urls, u.String())
  55. }
  56. }
  57. sort.Strings(urls)
  58. return urls
  59. }
  60. // Len returns the size of URLsMap.
  61. func (c URLsMap) Len() int {
  62. return len(c)
  63. }
  64. // parse parses the given string and returns a map listing the values specified for each key.
  65. func parse(s string) map[string][]string {
  66. m := make(map[string][]string)
  67. for s != "" {
  68. key := s
  69. if i := strings.IndexAny(key, ","); i >= 0 {
  70. key, s = key[:i], key[i+1:]
  71. } else {
  72. s = ""
  73. }
  74. if key == "" {
  75. continue
  76. }
  77. value := ""
  78. if i := strings.Index(key, "="); i >= 0 {
  79. key, value = key[:i], key[i+1:]
  80. }
  81. m[key] = append(m[key], value)
  82. }
  83. return m
  84. }