path.go 912 B

12345678910111213141516171819202122232425262728293031
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package pathutil implements utility functions for handling slash-separated
  5. // paths.
  6. package pathutil
  7. import "path"
  8. // CanonicalURLPath returns the canonical url path for p, which follows the rules:
  9. // 1. the path always starts with "/"
  10. // 2. replace multiple slashes with a single slash
  11. // 3. replace each '.' '..' path name element with equivalent one
  12. // 4. keep the trailing slash
  13. // The function is borrowed from stdlib http.cleanPath in server.go.
  14. func CanonicalURLPath(p string) string {
  15. if p == "" {
  16. return "/"
  17. }
  18. if p[0] != '/' {
  19. p = "/" + p
  20. }
  21. np := path.Clean(p)
  22. // path.Clean removes trailing slash except for root,
  23. // put the trailing slash back if necessary.
  24. if p[len(p)-1] == '/' && np != "/" {
  25. np += "/"
  26. }
  27. return np
  28. }