forked from ant0ine/go-json-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.go
65 lines (56 loc) · 1.82 KB
/
route.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
package rest
import (
"fmt"
"reflect"
"strings"
)
// Route defines a route. It's used with SetRoutes.
type Route struct {
// Any HTTP method. It will be used as uppercase to avoid common mistakes.
HttpMethod string
// A string like "/resource/:id.json".
// Placeholders supported are:
// :param that matches any char to the first '/' or '.'
// *splat that matches everything to the end of the string
// (placeholder names must be unique per PathExp)
PathExp string
// Code that will be executed when this route is taken.
Func HandlerFunc
}
// RouteObjectMethod creates a Route that points to an object method. It can be convenient to point to
// an object method instead of a function, this helper makes it easy by passing the object instance and
// the method name as parameters.
func RouteObjectMethod(httpMethod string, pathExp string, objectInstance interface{}, objectMethod string) *Route {
value := reflect.ValueOf(objectInstance)
funcValue := value.MethodByName(objectMethod)
if funcValue.IsValid() == false {
panic(fmt.Sprintf(
"Cannot find the object method %s on %s",
objectMethod,
value,
))
}
routeFunc := func(w ResponseWriter, r *Request) {
funcValue.Call([]reflect.Value{
reflect.ValueOf(w),
reflect.ValueOf(r),
})
}
return &Route{
HttpMethod: httpMethod,
PathExp: pathExp,
Func: routeFunc,
}
}
// MakePath generates the path corresponding to this Route and the provided path parameters.
// This is used for reverse route resolution.
func (route *Route) MakePath(pathParams map[string]string) string {
path := route.PathExp
for paramName, paramValue := range pathParams {
paramPlaceholder := ":" + paramName
splatPlaceholder := "*" + paramName
r := strings.NewReplacer(paramPlaceholder, paramValue, splatPlaceholder, paramValue)
path = r.Replace(path)
}
return path
}