urls.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2015 The etcd Authors
  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" && u.Scheme != "unix" && u.Scheme != "unixs" {
  36. return nil, fmt.Errorf("URL scheme must be http, https, unix, or unixs: %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 MustNewURLs(strs []string) URLs {
  51. urls, err := NewURLs(strs)
  52. if err != nil {
  53. panic(err)
  54. }
  55. return urls
  56. }
  57. func (us URLs) String() string {
  58. return strings.Join(us.StringSlice(), ",")
  59. }
  60. func (us *URLs) Sort() {
  61. sort.Sort(us)
  62. }
  63. func (us URLs) Len() int { return len(us) }
  64. func (us URLs) Less(i, j int) bool { return us[i].String() < us[j].String() }
  65. func (us URLs) Swap(i, j int) { us[i], us[j] = us[j], us[i] }
  66. func (us URLs) StringSlice() []string {
  67. out := make([]string, len(us))
  68. for i := range us {
  69. out[i] = us[i].String()
  70. }
  71. return out
  72. }