diff options
author | Francis Lavoie <[email protected]> | 2024-05-20 13:14:58 -0400 |
---|---|---|
committer | GitHub <[email protected]> | 2024-05-20 11:14:58 -0600 |
commit | a6a45ff6c56d2d0df1ac86f22d38997da3ba3b39 (patch) | |
tree | dbee9ea2735217fc1ecb2b38fb79daaacf811fe8 /context.go | |
parent | 73e094e1ddce4504971136d766fd70065a130f24 (diff) | |
download | caddy-a6a45ff6c56d2d0df1ac86f22d38997da3ba3b39.tar.gz caddy-a6a45ff6c56d2d0df1ac86f22d38997da3ba3b39.zip |
context: AppIfConfigured returns error; consider not-yet-provisioned modules (#6292)
* context: Add new `AppStrict()` method to avoid instantiating empty apps
* Rename AppStrict -> AppIfConfigured
---------
Co-authored-by: Matthew Holt <[email protected]>
Diffstat (limited to 'context.go')
-rw-r--r-- | context.go | 29 |
1 files changed, 13 insertions, 16 deletions
diff --git a/context.go b/context.go index 4307dda88..53d94a524 100644 --- a/context.go +++ b/context.go @@ -453,23 +453,20 @@ func (ctx Context) App(name string) (any, error) { return modVal, nil } -// AppIfConfigured returns an app by its name if it has been -// configured. Can be called instead of App() to avoid -// instantiating an empty app when that's not desirable. If -// the app has not been loaded, nil is returned. -// -// We return any type instead of the App type because it is not -// intended for the caller of this method to be the one to start -// or stop App modules. The caller is expected to assert to the -// concrete type. -func (ctx Context) AppIfConfigured(name string) any { - if ctx.cfg == nil { - // this can happen if the currently-active context - // is being accessed, but no config has successfully - // been loaded yet - return nil +// AppIfConfigured is like App, but it returns an error if the +// app has not been configured. This is useful when the app is +// required and its absence is a configuration error, or when +// the app is optional and you don't want to instantiate a +// new one that hasn't been explicitly configured. +func (ctx Context) AppIfConfigured(name string) (any, error) { + if app, ok := ctx.cfg.apps[name]; ok { + return app, nil + } + appRaw := ctx.cfg.AppsRaw[name] + if appRaw == nil { + return nil, fmt.Errorf("app module %s is not configured", name) } - return ctx.cfg.apps[name] + return ctx.App(name) } // Storage returns the configured Caddy storage implementation. |