From b552615e22224a497dda4bae89940eeb05c0cd53 Mon Sep 17 00:00:00 2001 From: Bulat Gaifullin Date: Tue, 18 Apr 2017 09:52:32 +0300 Subject: [PATCH] Added method Route.GetMethods --- mux_test.go | 23 +++++++++++++++++++++++ route.go | 16 ++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/mux_test.go b/mux_test.go index 1ccc920..d0584df 100644 --- a/mux_test.go +++ b/mux_test.go @@ -35,6 +35,7 @@ type routeTest struct { path string // the expected path of the match pathTemplate string // the expected path template to match hostTemplate string // the expected host template to match + methods []string // the expected route methods pathRegexp string // the expected path regexp shouldMatch bool // whether the request is expected to match the route at all shouldRedirect bool // whether the request should result in a redirect @@ -660,6 +661,7 @@ func TestMethods(t *testing.T) { vars: map[string]string{}, host: "", path: "", + methods: []string{"GET", "POST"}, shouldMatch: true, }, { @@ -669,6 +671,7 @@ func TestMethods(t *testing.T) { vars: map[string]string{}, host: "", path: "", + methods: []string{"GET", "POST"}, shouldMatch: true, }, { @@ -678,13 +681,25 @@ func TestMethods(t *testing.T) { vars: map[string]string{}, host: "", path: "", + methods: []string{"GET", "POST"}, shouldMatch: false, }, + { + title: "Route without methods", + route: new(Route), + request: newRequest("PUT", "http://localhost"), + vars: map[string]string{}, + host: "", + path: "", + methods: []string{}, + shouldMatch: true, + }, } for _, test := range tests { testRoute(t, test) testTemplate(t, test) + testMethods(t, test) } } @@ -1512,6 +1527,14 @@ func testTemplate(t *testing.T, test routeTest) { } } +func testMethods(t *testing.T, test routeTest) { + route := test.route + methods, _ := route.GetMethods() + if strings.Join(methods, ",") != strings.Join(test.methods, ",") { + t.Errorf("(%v) GetMethods not equal: expected %v, got %v", test.title, test.methods, methods) + } +} + func testRegexp(t *testing.T, test routeTest) { route := test.route routePathRegexp, regexpErr := route.GetPathRegexp() diff --git a/route.go b/route.go index d3ba6cd..a7c7d8c 100644 --- a/route.go +++ b/route.go @@ -572,6 +572,22 @@ func (r *Route) GetPathRegexp() (string, error) { return r.regexp.path.regexp.String(), nil } +// GetMethods returns the methods the route matches against +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An empty list will be returned if route does not have methods. +func (r *Route) GetMethods() ([]string, error) { + if r.err != nil { + return nil, r.err + } + for _, m := range r.matchers { + if methods, ok := m.(methodMatcher); ok { + return []string(methods), nil + } + } + return nil, nil +} + // GetHostTemplate returns the template used to build the // route match. // This is useful for building simple REST API documentation and for instrumentation