urls.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package types
  14. import (
  15. "errors"
  16. "fmt"
  17. "net"
  18. "net/url"
  19. "sort"
  20. "strings"
  21. )
  22. type URLs []url.URL
  23. func (us URLs) String() string {
  24. return strings.Join(us.StringSlice(), ",")
  25. }
  26. func (us *URLs) Sort() {
  27. sort.Sort(us)
  28. }
  29. func (us URLs) Len() int { return len(us) }
  30. func (us URLs) Less(i, j int) bool { return us[i].String() < us[j].String() }
  31. func (us URLs) Swap(i, j int) { us[i], us[j] = us[j], us[i] }
  32. func (us URLs) StringSlice() []string {
  33. out := make([]string, len(us))
  34. for i := range us {
  35. out[i] = us[i].String()
  36. }
  37. return out
  38. }
  39. func NewURLs(strs []string) (URLs, error) {
  40. all := make([]url.URL, len(strs))
  41. if len(all) == 0 {
  42. return nil, errors.New("no valid URLs given")
  43. }
  44. for i, in := range strs {
  45. in = strings.TrimSpace(in)
  46. u, err := url.Parse(in)
  47. if err != nil {
  48. return nil, err
  49. }
  50. if u.Scheme != "http" && u.Scheme != "https" {
  51. return nil, fmt.Errorf("URL scheme must be http or https: %s", in)
  52. }
  53. if _, _, err := net.SplitHostPort(u.Host); err != nil {
  54. return nil, fmt.Errorf(`URL address does not have the form "host:port": %s`, in)
  55. }
  56. if u.Path != "" {
  57. return nil, fmt.Errorf("URL must not contain a path: %s", in)
  58. }
  59. all[i] = *u
  60. }
  61. us := URLs(all)
  62. us.Sort()
  63. return us, nil
  64. }