urls.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package types
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/url"
  7. "sort"
  8. "strings"
  9. )
  10. type URLs []url.URL
  11. func (us *URLs) Sort() {
  12. sort.Sort(us)
  13. }
  14. func (us URLs) Len() int { return len(us) }
  15. func (us URLs) Less(i, j int) bool { return us[i].String() < us[j].String() }
  16. func (us URLs) Swap(i, j int) { us[i], us[j] = us[j], us[i] }
  17. func (us URLs) StringSlice() []string {
  18. out := make([]string, len(us))
  19. for i := range us {
  20. out[i] = us[i].String()
  21. }
  22. return out
  23. }
  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. }