-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
49 lines (40 loc) · 1.11 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
package route
import (
"errors"
"net/http"
"sync"
)
// inspired by Brad Fitzpatrick's idea:
// https://groups.google.com/forum/#!msg/golang-nuts/teSBtPvv1GQ/U12qA9N51uIJ
type context struct {
mutex sync.Mutex
params map[*http.Request]map[string]string // URL parameters.
}
// set stores a map of URL paramters for a given request.
func (c *context) set(req *http.Request, m map[string]string) {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.params == nil {
c.params = make(map[*http.Request]map[string]string)
}
c.params[req] = m
}
// Get returns an URL parameter value for a given key for a given request.
func (c *context) Get(req *http.Request, key string) (string, error) {
c.mutex.Lock()
defer c.mutex.Unlock()
if c.params == nil {
return "", errors.New("Parameters map has not been initialized")
}
val, ok := c.params[req][key]
if !ok {
return val, errors.New(key + " Key does not exist in the parameters map")
}
return val, nil
}
// clear removes all the key/value pairs for a given request.
func (c *context) clear(req *http.Request) {
c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.params, req)
}