Skip to content

Commit 88748eb

Browse files
committed
Router: add explicit error message when calling RegisterRoutes twice
1 parent 7748b33 commit 88748eb

File tree

3 files changed

+10
-3
lines changed

3 files changed

+10
-3
lines changed

router.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,7 @@ func NewRouter(server *Server) *Router {
138138

139139
// ClearRegexCache set internal router's regex cache used for route parameters optimisation to nil
140140
// so it can be garbage collected.
141-
// You don't need to call this function if you are using `goyave.Server`.
142-
// However, this method SHOULD be called by external tooling that build routers without starting the HTTP
143-
// server when they are done registering routes and subrouters.
141+
// You don't need to call this function if you are using `server.RegisterRoutes`.
144142
func (r *Router) ClearRegexCache() {
145143
r.regexCache = nil
146144
for _, subrouter := range r.subrouters {

server.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,9 @@ func (s *Server) Start() error {
490490
// The router's regex cache is cleared after the `routeRegistrer` function returns.
491491
// This method should only be called once.
492492
func (s *Server) RegisterRoutes(routeRegistrer func(*Server, *Router)) {
493+
if s.router.regexCache == nil {
494+
panic(errors.NewSkip("router's regex cache has already been cleared, did you call RegisterRoutes twice?", 3))
495+
}
493496
routeRegistrer(s, s.router)
494497
s.router.ClearRegexCache()
495498
}

server_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,12 @@ func TestServer(t *testing.T) {
340340
router.Get("/", func(_ *Response, _ *Request) {}).Name("base")
341341
})
342342
assert.NotNil(t, server.router.GetRoute("base"))
343+
344+
t.Run("panic_if_called_twice", func(t *testing.T) {
345+
assert.PanicsWithError(t, "router's regex cache has already been cleared, did you call RegisterRoutes twice?", func() {
346+
server.RegisterRoutes(func(_ *Server, _ *Router) {})
347+
})
348+
})
343349
})
344350

345351
t.Run("Transaction", func(t *testing.T) {

0 commit comments

Comments
 (0)