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

GO-4384 Add a non panicking method shouldcomponent #359

Merged
merged 3 commits into from
Dec 11, 2024
Merged
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
29 changes: 19 additions & 10 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ var (
)

var (
log = logger.NewNamed("app")
StopDeadline = time.Minute
StopWarningAfter = time.Second * 10
StartWarningAfter = time.Second * 10
log = logger.NewNamed("app")
StopDeadline = time.Minute
StopWarningAfter = time.Second * 10
StartWarningAfter = time.Second * 10
ErrComponentNotFound = errors.New("component not found")
)

// Component is a minimal interface for a common app.Component
Expand Down Expand Up @@ -179,22 +180,30 @@ func (app *App) MustComponent(name string) Component {
return s
}

// MustComponent - generic version of app.MustComponent
func MustComponent[i any](app *App) i {
func GetComponent[t any](app *App) (t, error) {
app.mu.RLock()
defer app.mu.RUnlock()
var empty t
current := app
for current != nil {
for _, s := range current.components {
if v, ok := s.(i); ok {
if v, ok := s.(t); ok {
app.onComponent(s)
return v
return v, nil
}
}
current = current.parent
}
empty := new(i)
panic(fmt.Errorf("component with interface %T is not found", empty))
return empty, ErrComponentNotFound
}

// MustComponent - generic version of app.MustComponent
func MustComponent[t any](app *App) t {
component, err := GetComponent[t](app)
if err != nil {
panic(fmt.Errorf("component with interface %T is not found", new(t)))
}
return component
}

// ComponentNames returns all registered names
Expand Down
Loading