-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
82 lines (72 loc) · 1.86 KB
/
context.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package nohtml
import (
"context"
"net/http"
"strings"
)
// New creates a context from a http request.
func New(r *http.Request) *Context {
// TODO: url decode path?
p := strings.Split(r.URL.Path, "/")
h := strings.Split(r.URL.Fragment, "/")
return &Context{r, nil, p, nil, h}
}
// Context tracks a request context.
type Context struct {
r *http.Request
path, rpath []string
hash, rhash []string
}
// Context returns the context.Context associated with the current request.
func (c *Context) Context() context.Context {
return c.r.Context()
}
// Path returns the first element in the request path and
// returns a sub-context (which has the rest of the path).
func (c *Context) Path() (string, *Context) {
for idx, p := range c.rpath {
if p != "" {
result := c.AppendPath(p)
result.rpath = c.rpath[idx+1:]
return p, result
}
}
return "", c
}
// AppendPath returns a new context with the provided path element
// appended to it.
func (c *Context) AppendPath(pathElement string) *Context {
result := *c
result.path = append(append([]string{}, result.path...), pathElement)
return &result
}
// Hash returns the first element in the request hash and
// returns a sub-context (which has the rest of the hash).
func (c *Context) Hash() (string, *Context) {
for idx, h := range c.rhash {
if h != "" {
result := c.AppendHash(h)
result.rhash = c.rhash[idx+1:]
return h, result
}
}
return "", c
}
// AppendHash returns a new context with the provided hash element
// appended to it.
func (c *Context) AppendHash(hashElement string) *Context {
result := *c
result.hash = append(append([]string{}, result.hash...), hashElement)
return &result
}
// HRef returns a valid HREF for the current scope
func (c *Context) HRef() string {
// TOOD: url encode shit?
result := ""
for _, p := range c.path {
if p != "" {
result += "/" + p
}
}
return result
}