path.go 824 B

1234567891011121314151617181920212223242526272829
  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
  5. import "path"
  6. // CanonicalURLPath returns the canonical url path for p, which follows the rules:
  7. // 1. the path always starts with "/"
  8. // 2. replace multiple slashes with a single slash
  9. // 3. replace each '.' '..' path name element with equivalent one
  10. // 4. keep the trailing slash
  11. // The function is borrowed from stdlib http.cleanPath in server.go.
  12. func CanonicalURLPath(p string) string {
  13. if p == "" {
  14. return "/"
  15. }
  16. if p[0] != '/' {
  17. p = "/" + p
  18. }
  19. np := path.Clean(p)
  20. // path.Clean removes trailing slash except for root,
  21. // put the trailing slash back if necessary.
  22. if p[len(p)-1] == '/' && np != "/" {
  23. np += "/"
  24. }
  25. return np
  26. }