summaryrefslogtreecommitdiff
path: root/srv/cfg
diff options
context:
space:
mode:
authorBrian Picciano <mediocregopher@gmail.com>2021-08-07 20:38:37 -0600
committerBrian Picciano <mediocregopher@gmail.com>2021-08-07 20:38:37 -0600
commit0197d9cd493b5785bca05f476856540ec64da64a (patch)
treedb19ac4bfa602b1e0b001769c57d6b7c37d96fc4 /srv/cfg
parentdce39b836a0fd6e37ab2499c2e0e232572c17ad6 (diff)
split configuration parsing out into separate packages, split api out as well
Diffstat (limited to 'srv/cfg')
-rw-r--r--srv/cfg/cfg.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/srv/cfg/cfg.go b/srv/cfg/cfg.go
new file mode 100644
index 0000000..08a9e53
--- /dev/null
+++ b/srv/cfg/cfg.go
@@ -0,0 +1,52 @@
+// Package cfg implements a simple wrapper around go's flag package, in order to
+// implement initialization hooks.
+package cfg
+
+import (
+ "context"
+ "flag"
+ "os"
+)
+
+// Cfger is a component which can be used with Cfg to setup its initialization.
+type Cfger interface {
+ SetupCfg(*Cfg)
+}
+
+// Cfg is a wrapper around the stdlib's FlagSet and a set of initialization
+// hooks.
+type Cfg struct {
+ *flag.FlagSet
+
+ hooks []func(ctx context.Context) error
+}
+
+// New initializes and returns a new instance of *Cfg.
+func New() *Cfg {
+ return &Cfg{
+ FlagSet: flag.NewFlagSet("", flag.ExitOnError),
+ }
+}
+
+// OnInit appends the given callback to the sequence of hooks which will run on
+// a call to Init.
+func (c *Cfg) OnInit(cb func(context.Context) error) {
+ c.hooks = append(c.hooks, cb)
+}
+
+// Init runs all hooks registered using OnInit, in the same order OnInit was
+// called. If one returns an error that error is returned and no further hooks
+// are run.
+func (c *Cfg) Init(ctx context.Context) error {
+ if err := c.FlagSet.Parse(os.Args[1:]); err != nil {
+ return err
+ }
+
+ for _, h := range c.hooks {
+ if err := h(ctx); err != nil {
+ return err
+ }
+ }
+
+ return nil
+}