Populate Go struct fields from environment variables, command-line arguments, and default values with a simple tag-based API.
Keep configuration loading simple and declarative using Go struct tags.
Populate structs directly from environment variables with minimal boilerplate.
Support CLI arguments as flags and parse values into your configuration structs.
Use default values and required validation to make struct initialization predictable.
Use tags to declare how each field should be populated.
Reads a value from an environment variable and parses it into the field.
Syntax: `env:"ENV_NAME"`
Supported types: string, bool, ints, uints, float32/64, time.Duration.
Reads a value from CLI arguments and assigns it to the field.
Syntax: `arg:"flag"`
Supported forms: --flag=value, -flag=value, --flag value, -flag value, and boolean flags like --debug.
Provides a fallback value when no env or arg value is present.
Syntax: `default:"value"`
Supported types: same as env and arg tags.
Marks a field as mandatory. If it remains zero-valued after parsing, an error is returned.
Syntax: `required:"true"` or `required:""`
This tag is evaluated last after env, arg, and default processing.
Pass a pointer to your struct into Parse and let StructParser populate the fields.
package main
import (
"fmt"
"github.com/vrianta/structparser"
)
type Config struct {
Host string `env:"APP_HOST" default:"localhost"`
Port int `env:"APP_PORT" default:"8080"`
Debug bool `arg:"debug" default:"false"`
ApiKey string `env:"APP_API_KEY" required:"true"`
}
func main() {
cfg := &Config{}
_, err := structparser.Parse(cfg, false)
if err != nil {
panic(err)
}
fmt.Printf("loaded config: %+v\n", cfg)
}
envargdefaultrequiredIf the struct is not a non-nil pointer, or if a required field remains empty, Parse returns an error.
Short examples for each tag type.
type Config struct {
ApiKey string `env:"APP_API_KEY" required:"true"`
Host string `env:"APP_HOST" default:"localhost"`
}
If APP_HOST is missing, Host falls back to localhost.
type Config struct {
Verbose bool `arg:"verbose" default:"false"`
}
Use --verbose or --verbose=true to enable the field.
type Config struct {
Mode string `default:"production"`
}
When no value is supplied, Mode becomes production.
type Config struct {
ApiKey string `env:"APP_API_KEY" required:"true"`
}
If the value is still zero-valued after parsing, Parse returns an error.
Important details for working with StructParser.
StructParser can only set exported fields because it uses reflection.
Use Go duration syntax like "30s" or "5m" for `time.Duration` values.
env is evaluated first, then arg, then default, and finally required.
Import the library from github.com/vrianta/golang/structparser and call structparser.Parse.