-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl.go
executable file
·53 lines (43 loc) · 1.04 KB
/
url.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
package scaffold
import (
"net/http"
"path"
"strings"
"golang.org/x/net/context"
)
func pathSplit(p string) []string {
p = strings.TrimSpace(p)
if p == "" {
return []string{}
}
p = path.Clean(p)
p = strings.TrimLeft(p, "/")
parts := strings.Split(p, "/")
var r []string
for _, str := range parts {
if str != "" {
r = append(r, str)
}
}
return r
}
// URLParts spliths a path into parts and caches it in the context
func URLParts(ctx context.Context, r *http.Request) (context.Context, []string) {
if ctx == nil {
ctx = context.Background()
}
if parts, ok := ctx.Value("scaffold_url_parts").([]string); ok {
return ctx, parts
}
parts := pathSplit(r.URL.Path)
ctx = context.WithValue(ctx, "scaffold_url_parts", parts)
return URLParts(ctx, r)
}
// URLPart returns a part of the url and caches it in the context
func URLPart(ctx context.Context, r *http.Request, i int) (context.Context, string, bool) {
ctx, parts := URLParts(ctx, r)
if len(parts) > i && i >= 0 {
return ctx, parts[i], true
}
return ctx, "", false
}