1
0
Fork 0
mirror of https://github.com/Luzifer/rconfig.git synced 2024-12-30 08:01:19 +00:00

Add ParseAndValidate method

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2017-06-19 14:22:33 +02:00
parent 31d785fa79
commit fbcc119420
Signed by: luzifer
GPG key ID: DC2729FDD34BE99E
2 changed files with 37 additions and 0 deletions

View file

@ -13,6 +13,7 @@ import (
"time"
"github.com/spf13/pflag"
validator "gopkg.in/validator.v2"
)
var (
@ -45,6 +46,15 @@ func Parse(config interface{}) error {
return parse(config, nil)
}
// ParseAndValidate works exactly like Parse but implements an additional run of
// the go-validator package on the configuration struct. Therefore additonal struct
// tags are supported like described in the readme file of the go-validator package:
//
// https://github.com/go-validator/validator/tree/v2#usage
func ParseAndValidate(config interface{}) error {
return parseAndValidate(config, nil)
}
// Args returns the non-flag command-line arguments.
func Args() []string {
return fs.Args()
@ -65,6 +75,14 @@ func SetVariableDefaults(defaults map[string]string) {
variableDefaults = defaults
}
func parseAndValidate(in interface{}, args []string) error {
if err := parse(in, args); err != nil {
return err
}
return validator.Validate(in)
}
func parse(in interface{}, args []string) error {
if args == nil {
args = os.Args

View file

@ -15,6 +15,10 @@ var _ = Describe("Testing general parsing", func() {
SadFlag string
}
type tValidated struct {
Test string `flag:"test" default:"" validate:"nonzero"`
}
var (
err error
args []string
@ -106,4 +110,19 @@ var _ = Describe("Testing general parsing", func() {
})
})
Context("making use of the validator package", func() {
var cfgValidated tValidated
BeforeEach(func() {
cfgValidated = tValidated{}
args = []string{}
})
JustBeforeEach(func() {
err = parseAndValidate(&cfgValidated, args)
})
It("should have errored", func() { Expect(err).To(HaveOccurred()) })
})
})