Skip to content

Commit

Permalink
Merge pull request #243 from go-martini/feature-get-routes
Browse files Browse the repository at this point in the history
Added GetAllRoutes to Routes interface
  • Loading branch information
codegangsta committed Apr 25, 2014
2 parents 6a15eeb + 8155718 commit c7203d5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
31 changes: 31 additions & 0 deletions router.go
Expand Up @@ -162,7 +162,14 @@ func (r *router) findRoute(name string) *route {
type Route interface {
// URLWith returns a rendering of the Route's url with the given string params.
URLWith([]string) string
// Name sets a name for the route.
Name(string)
// GetName returns the name of the route.
GetName() string
// Pattern returns the pattern of the route.
Pattern() string
// Method returns the method of the route.
Method() string
}

type route struct {
Expand Down Expand Up @@ -251,12 +258,26 @@ func (r *route) Name(name string) {
r.name = name
}

func (r *route) GetName() string {
return r.name
}

func (r *route) Pattern() string {
return r.pattern
}

func (r *route) Method() string {
return r.method
}

// Routes is a helper service for Martini's routing layer.
type Routes interface {
// URLFor returns a rendered URL for the given route. Optional params can be passed to fulfill named parameters in the route.
URLFor(name string, params ...interface{}) string
// MethodsFor returns an array of methods available for the path
MethodsFor(path string) []string
// GetAllRoutes returns an array with all the routes in the router.
All() []Route
}

// URLFor returns the url for the given route name.
Expand Down Expand Up @@ -284,6 +305,16 @@ func (r *router) URLFor(name string, params ...interface{}) string {
return route.URLWith(args)
}

func (r *router) All() []Route {
var ri = make([]Route, len(r.routes))

for i, route := range r.routes {
ri[i] = Route(route)
}

return ri
}

func hasMethod(methods []string, method string) bool {
for _, v := range methods {
if v == method {
Expand Down
18 changes: 18 additions & 0 deletions router_test.go
Expand Up @@ -418,3 +418,21 @@ func Test_URLFor(t *testing.T) {
context.MapTo(router, (*Routes)(nil))
router.Handle(recorder, req, context)
}

func Test_AllRoutes(t *testing.T) {
router := NewRouter()

patterns := []string{"/foo", "/fee", "/fii"}
methods := []string{"GET", "POST", "DELETE"}
names := []string{"foo", "fee", "fii"}

router.Get("/foo", func() {}).Name("foo")
router.Post("/fee", func() {}).Name("fee")
router.Delete("/fii", func() {}).Name("fii")

for i, r := range router.All() {
expect(t, r.Pattern(), patterns[i])
expect(t, r.Method(), methods[i])
expect(t, r.GetName(), names[i])
}
}

0 comments on commit c7203d5

Please sign in to comment.