From 5c8ba59790eb3f78453c426040f765c05b9ecf77 Mon Sep 17 00:00:00 2001 From: Conner Fromknecht Date: Mon, 1 Apr 2019 16:33:50 -0700 Subject: [PATCH] lncfg/interface: define Validator iface + variadic Validate This commit introduces the Validator interface, which is intended to be implemented by any sub configs. It specifies a Validate() error method that should fail if a sub configuration contains any invalid or insane parameters. In addition, a package-level Validate method can be used to check a variadic number of sub configs implementing the Validator interface. This allows the primary config struct to be extended via targeted and/or specialized sub configs, and validate all of them in sequence without bloating the main package with the actual validation logic. --- lncfg/interface.go | 21 +++++++++++++++++++++ lncfg/workers.go | 3 +++ 2 files changed, 24 insertions(+) create mode 100644 lncfg/interface.go diff --git a/lncfg/interface.go b/lncfg/interface.go new file mode 100644 index 00000000..78de294d --- /dev/null +++ b/lncfg/interface.go @@ -0,0 +1,21 @@ +package lncfg + +// Validator is a generic interface for validating sub configurations. +type Validator interface { + // Validate returns an error if a particular configuration is invalid or + // insane. + Validate() error +} + +// Validate accepts a variadic list of Validators and checks that each one +// passes its Validate method. An error is returned from the first Validator +// that fails. +func Validate(validators ...Validator) error { + for _, validator := range validators { + if err := validator.Validate(); err != nil { + return err + } + } + + return nil +} diff --git a/lncfg/workers.go b/lncfg/workers.go index 6bbacc5f..bbd9960b 100644 --- a/lncfg/workers.go +++ b/lncfg/workers.go @@ -47,3 +47,6 @@ func (w *Workers) Validate() error { return nil } + +// Compile-time constraint to ensure Workers implements the Validator interface. +var _ Validator = (*Workers)(nil)