Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "os"
- "reflect"
- )
- type AppConfig struct {
- Pg string `cli:"pg" env:"PG" default:"host=host.local dbname=db user=user password=password" description:"Connection to PostgreSQL"`
- Redis string `cli:"redis" env:"REDIS" default:"host.local" description:"Redis server"`
- }
- func main() {
- config := GetConfig(&AppConfig{})
- fmt.Println(config)
- }
- func GetConfig(config *AppConfig) *AppConfig {
- ref := reflect.TypeOf(*config)
- value := reflect.ValueOf(*config)
- for i := 0; i < value.NumField(); i++ {
- field := ref.Field(i)
- name := field.Tag.Get("env")
- if name != "" {
- env := os.Getenv(name)
- if env != "" {
- value.Field(i).SetString(env)
- } else {
- def := field.Tag.Get("default")
- if def != "" {
- value.Field(i).SetString(def)
- }
- }
- }
- /*
- cli := field.Tag.Get("cli")
- if cli != "" {
- flag.Var(value.Field(i).Pointer(), cli, field.Tag.Get("description"))
- }
- */
- }
- // flag.Parse()
- return config
- }
- panic: reflect: reflect.Value.SetString using unaddressable value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement