Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Panic if a route is registered twice #7

Merged
merged 1 commit into from
Oct 9, 2024
Merged
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
5 changes: 4 additions & 1 deletion router.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ func (r *Router) Run(ctx Context) error {
// Route a [Runner] with the given pattern.
// Routes are matched in the order they were added.
func (r *Router) Route(pattern string, runner Runner) {
if _, ok := r.runners[pattern]; ok {
panic("cannot add route which already exists")
}
r.patterns = append(r.patterns, pattern)
r.runners[pattern] = runner
}
Expand Down Expand Up @@ -76,7 +79,7 @@ type Middleware = func(next Runner) Runner
// If called in a [Scope], it will apply to all routes in that scope.
func (r *Router) Use(middlewares ...Middleware) {
if len(r.runners) > 0 {
panic("cannot use middlewares after adding routes")
panic("cannot add middlewares after adding routes")
}
r.middlewares = append(r.middlewares, middlewares...)
}
Expand Down
34 changes: 34 additions & 0 deletions router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,24 @@ func TestRouter_RouteFunc(t *testing.T) {
is.NotError(t, err)
is.True(t, called)
})

t.Run("panics if the route already exists", func(t *testing.T) {
r := clir.NewRouter()

r.RouteFunc("", func(ctx clir.Context) error {
return nil
})

defer func() {
if rec := recover(); rec == nil {
t.FailNow()
}
}()

r.RouteFunc("", func(ctx clir.Context) error {
return nil
})
})
}

func TestRouter_Use(t *testing.T) {
Expand Down Expand Up @@ -272,6 +290,22 @@ func TestRouter_Branch(t *testing.T) {
is.NotError(t, err)
is.Equal(t, "m1\nm2\ndance list\n", b.String())
})

t.Run("panics if the route already exists", func(t *testing.T) {
r := clir.NewRouter()

r.RouteFunc("", func(ctx clir.Context) error {
return nil
})

defer func() {
if rec := recover(); rec == nil {
t.FailNow()
}
}()

r.Branch("", func(r *clir.Router) {})
})
}

func newMiddleware(t *testing.T, name string) clir.Middleware {
Expand Down
Loading