fix(api): ignore nil route groups
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
0f20eaa7b8
commit
93bef3ed85
2 changed files with 39 additions and 0 deletions
21
api.go
21
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
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue