From bc4745512bd11d49962d71b18824c501b5273ddc Mon Sep 17 00:00:00 2001 From: infogulch Date: Fri, 26 Apr 2024 02:56:01 -0500 Subject: [PATCH] Add Config.Options() and Server.Stop() --- TODO.md | 3 +++ config.go | 9 +++++++++ instance.go | 7 ++----- server.go | 19 +++++++++++++------ 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/TODO.md b/TODO.md index e683b8f..c8ee81b 100644 --- a/TODO.md +++ b/TODO.md @@ -71,6 +71,9 @@ - [ ] Schema generator: https://gitlab.com/Screwtapello/sqlite-schema-diagram/-/blob/main/sqlite-schema-diagram.sql?ref_type=heads - [ ] Add a way to register additional routes dynamically during init - [ ] Organize docs according to https://diataxis.fr/ +- [ ] Research alternative template loading strategies: + - https://github.com/claceio/clace/blob/898932c1766d3e063c67caf1b9a744777fa437c3/internal/app/app.go#L261 + - https://github.com/unrolled/render # DONE diff --git a/config.go b/config.go index b95b51d..1a909f4 100644 --- a/config.go +++ b/config.go @@ -79,6 +79,15 @@ func (config *Config) Defaults() *Config { return config } +func (c *Config) Options(options ...Option) (*Config, error) { + for _, o := range options { + if err := o(c); err != nil { + return nil, fmt.Errorf("failed to apply xtemplate config option: %w", err) + } + } + return c, nil +} + type Option func(*Config) error func WithTemplateFS(fs fs.FS) Option { diff --git a/instance.go b/instance.go index 71960b7..0a55704 100644 --- a/instance.go +++ b/instance.go @@ -54,11 +54,8 @@ type Instance struct { func (config Config) Instance(cfgs ...Option) (*Instance, *InstanceStats, []InstanceRoute, error) { start := time.Now() - config.Defaults() - for _, c := range cfgs { - if err := c(&config); err != nil { - return nil, nil, nil, fmt.Errorf("failed to configure instance: %w", err) - } + if _, err := config.Defaults().Options(cfgs...); err != nil { + return nil, nil, nil, err } build := &builder{ diff --git a/server.go b/server.go index cda3993..1274e09 100644 --- a/server.go +++ b/server.go @@ -2,7 +2,6 @@ package xtemplate import ( "context" - "fmt" "log/slog" "net/http" "sync" @@ -30,11 +29,8 @@ type Server struct { // Build creates a new Server from an xtemplate.Config. func (config Config) Server(cfgs ...Option) (*Server, error) { - config.Defaults() - for _, c := range cfgs { - if err := c(&config); err != nil { - return nil, fmt.Errorf("failed to configure server: %w", err) - } + if _, err := config.Defaults().Options(cfgs...); err != nil { + return nil, err } config.Logger = config.Logger.WithGroup("xtemplate") @@ -107,3 +103,14 @@ func (x *Server) Reload(cfgs ...Option) error { log.Info("rebuild succeeded", slog.Int64("new_id", new_.id), slog.Duration("rebuild_time", time.Since(start))) return nil } + +func (x *Server) Stop() { + x.mutex.Lock() + defer x.mutex.Unlock() + + if x.cancel != nil { + x.cancel() + } + x.cancel = nil + x.instance.Store(nil) +}