urlsmap.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. "net/url"
  18. "sort"
  19. "strings"
  20. )
  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,mach0=http://2.2.2.2,mach1=http://3.3.3.3,mach2=http://4.4.4.4
  25. func NewURLsMap(s string) (URLsMap, error) {
  26. cl := URLsMap{}
  27. v, err := url.ParseQuery(strings.Replace(s, ",", "&", -1))
  28. if err != nil {
  29. return nil, err
  30. }
  31. for name, urls := range v {
  32. if len(urls) == 0 || urls[0] == "" {
  33. return nil, fmt.Errorf("empty URL given for %q", name)
  34. }
  35. us, err := NewURLs(urls)
  36. if err != nil {
  37. return nil, err
  38. }
  39. cl[name] = us
  40. }
  41. return cl, nil
  42. }
  43. // String returns NameURLPairs into discovery-formatted name-to-URLs sorted by name.
  44. func (c URLsMap) String() string {
  45. pairs := make([]string, 0)
  46. for name, urls := range c {
  47. for _, url := range urls {
  48. pairs = append(pairs, fmt.Sprintf("%s=%s", name, url.String()))
  49. }
  50. }
  51. sort.Strings(pairs)
  52. return strings.Join(pairs, ",")
  53. }
  54. // URLs returns a list of all URLs.
  55. // The returned list is sorted in ascending lexicographical order.
  56. func (c URLsMap) URLs() []string {
  57. urls := make([]string, 0)
  58. for _, us := range c {
  59. for _, u := range us {
  60. urls = append(urls, u.String())
  61. }
  62. }
  63. sort.Strings(urls)
  64. return urls
  65. }