penv.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package penv
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "golang.org/x/text/cases"
  10. "golang.org/x/text/language"
  11. )
  12. const NoDescription = "No description"
  13. var Prefix = "ENV_"
  14. type DumpVar struct {
  15. Name string
  16. NameEnv string
  17. NameFlag string
  18. Desc string
  19. Type string
  20. Value string
  21. Secret bool
  22. }
  23. func generate(name string) string {
  24. n := ""
  25. prevBig := true
  26. for i, char := range name {
  27. if i > 0 && string(char) == strings.ToUpper(string(char)) && !prevBig {
  28. n += "_"
  29. }
  30. if string(char) == strings.ToUpper(string(char)) {
  31. prevBig = true
  32. } else {
  33. prevBig = false
  34. }
  35. n += string(char)
  36. }
  37. return n
  38. }
  39. func generateEnvName(name string) string {
  40. return strings.ToUpper(Prefix + generate(name))
  41. }
  42. func generateFlagName(name string) string {
  43. return strings.ToLower(generate(name))
  44. }
  45. func isEnvPassed(name string) bool {
  46. if _, ok := os.LookupEnv(name); ok {
  47. return true
  48. }
  49. return false
  50. }
  51. func isFlagPassed(name string) bool {
  52. res := false
  53. flag.Visit(func(f *flag.Flag) {
  54. if f.Name == name {
  55. res = true
  56. return
  57. }
  58. })
  59. return res
  60. }
  61. func stringToInt(value string) (int, error) {
  62. return strconv.Atoi(value)
  63. }
  64. func stringToInt64(value string) (int64, error) {
  65. return strconv.ParseInt(value, 10, 64)
  66. }
  67. func DumpConfig(config any) map[string]DumpVar {
  68. res := map[string]DumpVar{}
  69. v := reflect.ValueOf(config).Elem()
  70. t := v.Type()
  71. for i := 0; i < t.NumField(); i++ {
  72. nameEnv := generateEnvName(t.Field(i).Name)
  73. fieldType := t.Field(i).Type.Kind().String()
  74. nameFlag := generateFlagName(t.Field(i).Name)
  75. description := t.Field(i).Tag.Get("description")
  76. if description == "" {
  77. description = NoDescription
  78. }
  79. secret := t.Field(i).Tag.Get("secret")
  80. if fieldType == "string" {
  81. res[t.Field(i).Name] = DumpVar{
  82. Name: t.Field(i).Name,
  83. NameEnv: nameEnv,
  84. NameFlag: nameFlag,
  85. Desc: description,
  86. Type: cases.Title(language.English).String(fieldType),
  87. Value: *v.Field(i).Addr().Interface().(*string),
  88. Secret: secret == "1" || secret == "true",
  89. }
  90. } else if fieldType == "int" {
  91. res[t.Field(i).Name] = DumpVar{
  92. Name: t.Field(i).Name,
  93. NameEnv: nameEnv,
  94. NameFlag: nameFlag,
  95. Desc: description,
  96. Type: cases.Title(language.English).String(fieldType),
  97. Value: fmt.Sprintf("%d", *v.Field(i).Addr().Interface().(*int)),
  98. Secret: secret == "1" || secret == "true",
  99. }
  100. } else if fieldType == "int64" {
  101. res[t.Field(i).Name] = DumpVar{
  102. Name: t.Field(i).Name,
  103. NameEnv: nameEnv,
  104. NameFlag: nameFlag,
  105. Desc: description,
  106. Type: cases.Title(language.English).String(fieldType),
  107. Value: fmt.Sprintf("%d", *v.Field(i).Addr().Interface().(*int64)),
  108. Secret: secret == "1" || secret == "true",
  109. }
  110. }
  111. }
  112. return res
  113. }
  114. // ProcessConfig automaticaly read flags and ENVs to structure.
  115. //
  116. // config - must be a pointer to structure
  117. //
  118. // var Config struct {
  119. // Deployment string `default:"development"`
  120. // Host string `default:"127.0.0.1"`
  121. // Port string `default:"8080"`
  122. // }
  123. //
  124. // func init() {
  125. // if err := penv.ProcessConfig(&Config); err != nil {
  126. // panic(err)
  127. // }
  128. // }
  129. func ProcessConfig(config any) error {
  130. v := reflect.ValueOf(config).Elem()
  131. t := v.Type()
  132. // Flags
  133. for i := 0; i < t.NumField(); i++ {
  134. nameEnv := generateEnvName(t.Field(i).Name)
  135. nameFlag := generateFlagName(t.Field(i).Name)
  136. fieldType := t.Field(i).Type.Kind().String()
  137. defvalue := t.Field(i).Tag.Get("default")
  138. description := t.Field(i).Tag.Get("description")
  139. if description == "" {
  140. description = NoDescription
  141. }
  142. if fieldType == "string" {
  143. value := v.Field(i).Addr().Interface().(*string)
  144. flag.StringVar(value, nameFlag, defvalue, "Or "+nameEnv+": "+description)
  145. } else if fieldType == "int" {
  146. if ndefvalue, err := stringToInt(defvalue); err == nil {
  147. value := v.Field(i).Addr().Interface().(*int)
  148. flag.IntVar(value, nameFlag, ndefvalue, "Or "+nameEnv+": "+description)
  149. } else {
  150. return err
  151. }
  152. } else if fieldType == "int64" {
  153. if ndefvalue, err := stringToInt64(defvalue); err == nil {
  154. value := v.Field(i).Addr().Interface().(*int64)
  155. flag.Int64Var(value, nameFlag, ndefvalue, "Or "+nameEnv+": "+description)
  156. } else {
  157. return err
  158. }
  159. }
  160. }
  161. flag.Parse()
  162. // ENVs
  163. for i := 0; i < t.NumField(); i++ {
  164. nameEnv := generateEnvName(t.Field(i).Name)
  165. fieldType := t.Field(i).Type.Kind().String()
  166. if os.Getenv(nameEnv) != "" {
  167. if fieldType == "string" {
  168. value := v.Field(i).Addr().Interface().(*string)
  169. *value = os.Getenv(nameEnv)
  170. } else if fieldType == "int" {
  171. if nvalue, err := stringToInt(os.Getenv(nameEnv)); err == nil {
  172. value := v.Field(i).Addr().Interface().(*int)
  173. *value = nvalue
  174. } else {
  175. return err
  176. }
  177. } else if fieldType == "int64" {
  178. if nvalue, err := stringToInt64(os.Getenv(nameEnv)); err == nil {
  179. value := v.Field(i).Addr().Interface().(*int64)
  180. *value = nvalue
  181. } else {
  182. return err
  183. }
  184. }
  185. }
  186. }
  187. // Required
  188. for i := 0; i < t.NumField(); i++ {
  189. nameEnv := generateEnvName(t.Field(i).Name)
  190. nameFlag := generateFlagName(t.Field(i).Name)
  191. required := t.Field(i).Tag.Get("required")
  192. if required == "1" || required == "true" {
  193. if !(isEnvPassed(nameEnv) || isFlagPassed(nameFlag)) {
  194. return fmt.Errorf("variable '" + nameEnv + "' or flag '" + nameFlag + "' is not set")
  195. }
  196. }
  197. }
  198. return nil
  199. }