Documentation
¶
Overview ¶
Package cleanenv gives you a single tool to read application configuration from several sources.
You can just prepare config structure and fill it from the config file and environment variables.
type Config struct {
Port string `yml:"port" env:"PORT" env-default:"8080"`
Host string `yml:"host" env:"HOST" env-default:"localhost"`
}
var cfg Config
ReadConfig("config.yml", &cfg)
Index ¶
Constants ¶
const (
// DefaultSeparator is a defauld list and map separator character
DefaultSeparator = ","
)
Variables ¶
This section is empty.
Functions ¶
func GetDescription ¶
GetDescription returns a description of environment variables. You can provide a custom header text.
Example
type ConfigServer struct {
Port string `env:"PORT" env-description:"server port" env-default:"localhost"`
Host string `env:"HOST" env-description:"server host" env-default:"8080"`
}
var cfg ConfigRemote
help, err := cleanenv.GetDescription(&cfg, nil)
if err != nil {
...
}
You will get the following:
Environment variables:
PORT string
server port (default "localhost")
HOST string
server host (default "8080")
func ReadConfig ¶
ReadConfig reads configuration file and parses it depending on tags in structure provided. Then it reads and parses
Example:
type ConfigDatabase struct {
Port string `yml:"port" env:"PORT" env-default:"5432"`
Host string `yml:"host" env:"HOST" env-default:"localhost"`
Name string `yml:"name" env:"NAME" env-default:"postgres"`
User string `yml:"user" env:"USER" env-default:"user"`
Password string `yml:"password" env:"PASSWORD"`
}
var cfg ConfigDatabase
err := cleanenv.ReadConfig("config.yml", &cfg)
if err != nil {
...
}
func ReadEnv ¶
func ReadEnv(cfg interface{}) error
ReadEnv reads environment variables into the structure.
Example:
type ConfigDatabase struct {
Port string `env:"PORT" env-default:"5432"`
Host string `env:"HOST" env-default:"localhost"`
Name string `env:"NAME" env-default:"postgres"`
User string `env:"USER" env-default:"user"`
Password string `env:"PASSWORD"`
}
var cfg ConfigDatabase
err := cleanenv.ReadEnv(&cfg)
if err != nil {
...
}
func UpdateEnv ¶
func UpdateEnv(cfg interface{}) error
UpdateEnv rereads (updates) environment variables in the structure.
To mark the field as updatable provide the tag "env-upd"
Example:
type ConfigRemote struct {
Port string `env:"PORT" env-upd`
Host string `env:"HOST" env-upd`
UserName string `env:"USERNAME"`
}
var cfg ConfigRemote
cleanenv.ReadEnv(&cfg)
// ... some actions in-between
err := cleanenv.UpdateEnv(&cfg)
if err != nil {
...
}
Types ¶
type Setter ¶
Setter is an interface for a custom value setter.
To implement a custom value setter you need to add a SetValue function to your type that will receive a string raw value:
type MyField string
func (f MyField) SetValue(s string) error {
if s == "" {
return fmt.Errorf("field value can't be empty")
}
f = MyField("my field is: "+ s)
return nil
}