-
Notifications
You must be signed in to change notification settings - Fork 89
/
relativeurl.go
62 lines (56 loc) · 1.88 KB
/
relativeurl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright 2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package utils
import (
"strings"
"github.com/juju/errors"
)
// RelativeURLPath returns a relative URL path that is lexically
// equivalent to targpath when interpreted by url.URL.ResolveReference.
// On success, the returned path will always be non-empty and relative
// to basePath, even if basePath and targPath share no elements.
//
// It is assumed that both basePath and targPath are normalized
// (have no . or .. elements).
//
// An error is returned if basePath or targPath are not absolute paths.
func RelativeURLPath(basePath, targPath string) (string, error) {
if !strings.HasPrefix(basePath, "/") {
return "", errors.New("non-absolute base URL")
}
if !strings.HasPrefix(targPath, "/") {
return "", errors.New("non-absolute target URL")
}
baseParts := strings.Split(basePath, "/")
targParts := strings.Split(targPath, "/")
// For the purposes of dotdot, the last element of
// the paths are irrelevant. We save the last part
// of the target path for later.
lastElem := targParts[len(targParts)-1]
baseParts = baseParts[0 : len(baseParts)-1]
targParts = targParts[0 : len(targParts)-1]
// Find the common prefix between the two paths:
var i int
for ; i < len(baseParts); i++ {
if i >= len(targParts) || baseParts[i] != targParts[i] {
break
}
}
dotdotCount := len(baseParts) - i
targOnly := targParts[i:]
result := make([]string, 0, dotdotCount+len(targOnly)+1)
for i := 0; i < dotdotCount; i++ {
result = append(result, "..")
}
result = append(result, targOnly...)
result = append(result, lastElem)
final := strings.Join(result, "/")
if final == "" {
// If the final result is empty, the last element must
// have been empty, so the target was slash terminated
// and there were no previous elements, so "."
// is appropriate.
final = "."
}
return final, nil
}