Advertisement
Guest User

Untitled

a guest
Nov 18th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "os"
  6. "reflect"
  7. )
  8.  
  9. type AppConfig struct {
  10. Pg string `cli:"pg" env:"PG" default:"host=host.local dbname=db user=user password=password" description:"Connection to PostgreSQL"`
  11. Redis string `cli:"redis" env:"REDIS" default:"host.local" description:"Redis server"`
  12. }
  13.  
  14. func main() {
  15. config := GetConfig(&AppConfig{})
  16. fmt.Println(config)
  17. }
  18.  
  19. func GetConfig(config *AppConfig) *AppConfig {
  20. ref := reflect.TypeOf(*config)
  21. value := reflect.ValueOf(*config)
  22. for i := 0; i < value.NumField(); i++ {
  23. field := ref.Field(i)
  24.  
  25. name := field.Tag.Get("env")
  26. if name != "" {
  27. env := os.Getenv(name)
  28. if env != "" {
  29. value.Field(i).SetString(env)
  30. } else {
  31. def := field.Tag.Get("default")
  32. if def != "" {
  33. value.Field(i).SetString(def)
  34. }
  35. }
  36. }
  37. /*
  38. cli := field.Tag.Get("cli")
  39. if cli != "" {
  40. flag.Var(value.Field(i).Pointer(), cli, field.Tag.Get("description"))
  41. }
  42. */
  43. }
  44. // flag.Parse()
  45. return config
  46. }
  47.  
  48. panic: reflect: reflect.Value.SetString using unaddressable value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement