From f0216967dca12831b1aac351fc8c4bfcea148697 Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Tue, 5 Jan 2021 14:39:30 -0700 Subject: caddyfile: Refactor unmarshaling of module tokens Eliminates a fair amount of repeated code --- caddyconfig/caddyfile/adapter.go | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'caddyconfig/caddyfile') diff --git a/caddyconfig/caddyfile/adapter.go b/caddyconfig/caddyfile/adapter.go index 8d624f1..185816b 100644 --- a/caddyconfig/caddyfile/adapter.go +++ b/caddyconfig/caddyfile/adapter.go @@ -94,5 +94,31 @@ type ServerType interface { Setup([]ServerBlock, map[string]interface{}) (*caddy.Config, []caddyconfig.Warning, error) } +// UnmarshalModule instantiates a module with the given ID and invokes +// UnmarshalCaddyfile on the new value using the immediate next segment +// of d as input. In other words, d's next token should be the first +// token of the module's Caddyfile input. +// +// This function is used when the next segment of Caddyfile tokens +// belongs to another Caddy module. The returned value is often +// type-asserted to the module's associated type for practical use +// when setting up a config. +func UnmarshalModule(d *Dispenser, moduleID string) (Unmarshaler, error) { + mod, err := caddy.GetModule(moduleID) + if err != nil { + return nil, d.Errf("getting module named '%s': %v", moduleID, err) + } + inst := mod.New() + unm, ok := inst.(Unmarshaler) + if !ok { + return nil, d.Errf("module %s is not a Caddyfile unmarshaler; is %T", mod.ID, inst) + } + err = unm.UnmarshalCaddyfile(d.NewFromNextSegment()) + if err != nil { + return nil, err + } + return unm, nil +} + // Interface guard var _ caddyconfig.Adapter = (*Adapter)(nil) -- cgit v1.2.3