Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,21 @@ func TestGroup_multiLevelGroup(t *testing.T) {
assert.Equal(t, `OK`, body)
}

func TestGroup_pathWithoutLeadingSlash(t *testing.T) {
e := New()
g := e.Group("/v1")
g.GET("posts", func(c *Context) error {
return c.String(http.StatusOK, "ok")
})

status, body := request(http.MethodGet, "/v1/posts", e)
assert.Equal(t, http.StatusOK, status)
assert.Equal(t, "ok", body)

status, _ = request(http.MethodGet, "/v1posts", e)
assert.Equal(t, http.StatusNotFound, status)
}

func TestGroupFile(t *testing.T) {
e := New()
g := e.Group("/group")
Expand Down
18 changes: 17 additions & 1 deletion route.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,25 @@ func (r Route) ToRouteInfo(params []string) RouteInfo {
}
}

// joinPathPrefix concatenates a group prefix and a route path.
// A missing slash between "/v1" and "posts" used to produce "/v1posts".
// Wildcard suffixes (`*` / `/*`) stay concatenated so Group.Static("") keeps `/prefix*`.
func joinPathPrefix(prefix, path string) string {
if prefix == "" {
return path
}
if path == "" {
return prefix
}
if prefix[len(prefix)-1] != '/' && path[0] != '/' && path[0] != '*' {
return prefix + "/" + path
}
return prefix + path
}

// WithPrefix recreates Route with added group prefix and group middlewares it is grouped to.
func (r Route) WithPrefix(pathPrefix string, middlewares []MiddlewareFunc) Route {
r.Path = pathPrefix + r.Path
r.Path = joinPathPrefix(pathPrefix, r.Path)

if len(middlewares) > 0 {
m := make([]MiddlewareFunc, 0, len(middlewares)+len(r.Middlewares))
Expand Down
21 changes: 21 additions & 0 deletions route_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,27 @@ func TestRoute_ForGroup(t *testing.T) {
assert.Equal(t, r.Name, "test route")
}

func TestJoinPathPrefix(t *testing.T) {
tests := []struct {
prefix string
path string
want string
}{
{prefix: "/v1", path: "/posts", want: "/v1/posts"},
{prefix: "/v1", path: "posts", want: "/v1/posts"},
{prefix: "/v1/", path: "posts", want: "/v1/posts"},
{prefix: "/v1/", path: "/posts", want: "/v1//posts"},
{prefix: "/users", path: "/test", want: "/users/test"},
{prefix: "/users", path: ":id", want: "/users/:id"},
{prefix: "/test", path: "*", want: "/test*"},
{prefix: "", path: "posts", want: "posts"},
{prefix: "/v1", path: "", want: "/v1"},
}
for _, tt := range tests {
assert.Equal(t, tt.want, joinPathPrefix(tt.prefix, tt.path), "prefix=%q path=%q", tt.prefix, tt.path)
}
}

func exampleRoutes() Routes {
return Routes{
RouteInfo{
Expand Down