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