url.go 796 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package missinggo
  2. import (
  3. "net/url"
  4. "path"
  5. )
  6. // Returns URL opaque as an unrooted path.
  7. func URLOpaquePath(u *url.URL) string {
  8. if u.Opaque != "" {
  9. return u.Opaque
  10. }
  11. return u.Path
  12. }
  13. // Cleans the (absolute) URL path, removing unnecessary . and .. elements. See
  14. // "net/http".cleanPath.
  15. func CleanURLPath(p string) string {
  16. if p == "" {
  17. return "/"
  18. }
  19. if p[0] != '/' {
  20. p = "/" + p
  21. }
  22. cp := path.Clean(p)
  23. // Add the trailing slash back, as it's relevant to a URL.
  24. if p[len(p)-1] == '/' && cp != "/" {
  25. cp += "/"
  26. }
  27. return cp
  28. }
  29. func URLJoinSubPath(base, rel string) string {
  30. baseURL, err := url.Parse(base)
  31. if err != nil {
  32. // Honey badger doesn't give a fuck.
  33. panic(err)
  34. }
  35. rel = CleanURLPath(rel)
  36. baseURL.Path = path.Join(baseURL.Path, rel)
  37. return baseURL.String()
  38. }