urls.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. "errors"
  17. "fmt"
  18. "net"
  19. "net/url"
  20. "sort"
  21. "strings"
  22. )
  23. type URLs []url.URL
  24. func NewURLs(strs []string) (URLs, error) {
  25. all := make([]url.URL, len(strs))
  26. if len(all) == 0 {
  27. return nil, errors.New("no valid URLs given")
  28. }
  29. for i, in := range strs {
  30. in = strings.TrimSpace(in)
  31. u, err := url.Parse(in)
  32. if err != nil {
  33. return nil, err
  34. }
  35. if u.Scheme != "http" && u.Scheme != "https" {
  36. return nil, fmt.Errorf("URL scheme must be http or https: %s", in)
  37. }
  38. if _, _, err := net.SplitHostPort(u.Host); err != nil {
  39. return nil, fmt.Errorf(`URL address does not have the form "host:port": %s`, in)
  40. }
  41. if u.Path != "" {
  42. return nil, fmt.Errorf("URL must not contain a path: %s", in)
  43. }
  44. all[i] = *u
  45. }
  46. us := URLs(all)
  47. us.Sort()
  48. return us, nil
  49. }
  50. func (us URLs) String() string {
  51. return strings.Join(us.StringSlice(), ",")
  52. }
  53. func (us *URLs) Sort() {
  54. sort.Sort(us)
  55. }
  56. func (us URLs) Len() int { return len(us) }
  57. func (us URLs) Less(i, j int) bool { return us[i].String() < us[j].String() }
  58. func (us URLs) Swap(i, j int) { us[i], us[j] = us[j], us[i] }
  59. func (us URLs) StringSlice() []string {
  60. out := make([]string, len(us))
  61. for i := range us {
  62. out[i] = us[i].String()
  63. }
  64. return out
  65. }