-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathparams.go
57 lines (48 loc) · 1.62 KB
/
params.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
package kami
import (
"golang.org/x/net/context"
)
type paramsKey struct{}
type panicKey struct{}
// Param returns a request path parameter, or a blank string if it doesn't exist.
// For example, with the path /v2/papers/:page
// use kami.Param(ctx, "page") to access the :page variable.
func Param(ctx context.Context, name string) string {
params, ok := ctx.Value(paramsKey{}).(map[string]string)
if !ok {
return ""
}
return params[name]
}
// SetParam will set the value of a path parameter in a given context.
// This is intended for testing and should not be used otherwise.
func SetParam(ctx context.Context, name string, value string) context.Context {
params, ok := ctx.Value(paramsKey{}).(map[string]string)
if !ok {
params = map[string]string{name: value}
return context.WithValue(ctx, paramsKey{}, params)
}
params[name] = value
return ctx
}
// Exception gets the "v" in panic(v). The panic details.
// Only PanicHandler will receive a context you can use this with.
func Exception(ctx context.Context) interface{} {
return ctx.Value(panicKey{})
}
func newContextWithParams(ctx context.Context, params map[string]string) context.Context {
return context.WithValue(ctx, paramsKey{}, params)
}
func mergeParams(ctx context.Context, params map[string]string) context.Context {
current, _ := ctx.Value(paramsKey{}).(map[string]string)
if current == nil {
return context.WithValue(ctx, paramsKey{}, params)
}
for k, v := range params {
current[k] = v
}
return ctx
}
func newContextWithException(ctx context.Context, exception interface{}) context.Context {
return context.WithValue(ctx, panicKey{}, exception)
}