Replies: 1 comment 2 replies
-
Hey @cheshirex Here is one way I consider better: type Config struct {
Address string
Port int
}
func (c Config) Validate() error {
if c.Address == "" {
return errors.New("address is required")
}
if c.Port < 1024 || c.Port > 5000 {
return errors.New("port must be between 1024 and 5000")
}
} It's simple and elegant. Viper does one thing which is configuration loading. Adding features like validation would make the library more complex with little benefit. Hope that helps. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I didn't find anything like this in my searches, so apologies if this already exists and I just missed it.
I'm generally using Viper by unmarshaling a configuration into a structure.
What about having a feature to specify valid values, in terms of ranges or a specific set of possibilities? As an example, let's say you have a configuration specifying a port number. The range can be mostly restricted to a valid port by unmarshalling it into a uint16, for instance, but that still leaves 0 as a valid value that you might not want. Or maybe we'd want to restrict it further by saying it has to be a userspace port, so anything 1024 or less is no good.
Other possibilities along this line might be having a string that must be one of a set of possibilities -- it can be "aaa" or "bbb" but not anything that isn't pre-defined.
At the moment I validate this in my code by unmarshalling into a structure, and then calling a function that goes through all the relevant values and ensures they are valid.
Or if there's a better way to deal with things like this, I'm open to being enlightened. :-)
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions