From 93bef3ed85c80bb995e12f47a0c168113da38f63 Mon Sep 17 00:00:00 2001 From: Virgil Date: Wed, 1 Apr 2026 23:40:14 +0000 Subject: [PATCH] fix(api): ignore nil route groups Co-Authored-By: Virgil --- api.go | 21 +++++++++++++++++++++ modernization_test.go | 18 ++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/api.go b/api.go index dddae8e..e21cc16 100644 --- a/api.go +++ b/api.go @@ -9,6 +9,7 @@ import ( "errors" "iter" "net/http" + "reflect" "slices" "time" @@ -78,6 +79,9 @@ func (e *Engine) GroupsIter() iter.Seq[RouteGroup] { // Register adds a route group to the engine. func (e *Engine) Register(group RouteGroup) { + if isNilRouteGroup(group) { + return + } e.groups = append(e.groups, group) } @@ -174,6 +178,9 @@ func (e *Engine) build() *gin.Engine { // Mount each registered group at its base path. for _, g := range e.groups { + if isNilRouteGroup(g) { + continue + } rg := r.Group(g.BasePath()) g.RegisterRoutes(rg) } @@ -225,3 +232,17 @@ func (e *Engine) build() *gin.Engine { return r } + +func isNilRouteGroup(group RouteGroup) bool { + if group == nil { + return true + } + + value := reflect.ValueOf(group) + switch value.Kind() { + case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice: + return value.IsNil() + default: + return false + } +} diff --git a/modernization_test.go b/modernization_test.go index 60b3662..776d8f6 100644 --- a/modernization_test.go +++ b/modernization_test.go @@ -94,6 +94,24 @@ func TestEngine_ChannelsIter_Good_SnapshotsCurrentChannels(t *testing.T) { } } +func TestEngine_Register_Good_IgnoresNilGroups(t *testing.T) { + e, _ := api.New() + + var nilGroup *healthGroup + e.Register(nilGroup) + + g1 := &healthGroup{} + e.Register(g1) + + groups := e.Groups() + if len(groups) != 1 { + t.Fatalf("expected 1 registered group, got %d", len(groups)) + } + if groups[0].Name() != "health-extra" { + t.Fatalf("expected the original group to be preserved, got %q", groups[0].Name()) + } +} + func TestToolBridge_Iterators(t *testing.T) { b := api.NewToolBridge("/tools") desc := api.ToolDescriptor{Name: "test", Group: "g1"}