urls.go 975 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package flags
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/url"
  6. "strings"
  7. )
  8. // URLs implements the flag.Value interface to allow users to define multiple
  9. // URLs on the command-line
  10. type URLs []url.URL
  11. // Set parses a command line set of URLs formatted like:
  12. // http://127.0.0.1:7001,http://10.1.1.2:80
  13. func (us *URLs) Set(s string) error {
  14. strs := strings.Split(s, ",")
  15. all := make([]url.URL, len(strs))
  16. if len(all) == 0 {
  17. return errors.New("no valid URLs given")
  18. }
  19. for i, in := range strs {
  20. in = strings.TrimSpace(in)
  21. u, err := url.Parse(in)
  22. if err != nil {
  23. return err
  24. }
  25. if u.Scheme != "http" && u.Scheme != "https" {
  26. return fmt.Errorf("URL scheme must be http or https: %s", s)
  27. }
  28. if u.Path != "" {
  29. return fmt.Errorf("URL must not contain a path: %s", s)
  30. }
  31. all[i] = *u
  32. }
  33. *us = all
  34. return nil
  35. }
  36. func (us *URLs) String() string {
  37. all := make([]string, len(*us))
  38. for i, u := range *us {
  39. all[i] = u.String()
  40. }
  41. return strings.Join(all, ",")
  42. }