config_env.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package dns
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/cert/config"
  4. "github.com/BurntSushi/toml"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type Configuration struct {
  10. Credentials map[string]string `json:"credentials"`
  11. Additional map[string]string `json:"additional"`
  12. }
  13. type Links struct {
  14. API string `json:"api"`
  15. GoClient string `json:"go_client"`
  16. }
  17. type Config struct {
  18. Name string `json:"name"`
  19. Code string `json:"code"`
  20. Configuration *Configuration `json:"configuration,omitempty"`
  21. Links *Links `json:"links,omitempty"`
  22. }
  23. var configurations []Config
  24. var configurationMap map[string]Config
  25. func init() {
  26. filenames, err := config.ListConfigs()
  27. if err != nil {
  28. log.Fatalln(err)
  29. }
  30. configurationMap = make(map[string]Config)
  31. for _, filename := range filenames {
  32. if !strings.HasSuffix(filename, ".toml") {
  33. continue
  34. }
  35. data, err := config.GetConfig(filename)
  36. if err != nil {
  37. log.Fatalln(err)
  38. }
  39. c := Config{}
  40. err = toml.Unmarshal(data, &c)
  41. if err != nil {
  42. log.Fatalln(err)
  43. }
  44. configurationMap[c.Code] = c
  45. c.Configuration = nil
  46. c.Links = nil
  47. configurations = append(configurations, c)
  48. }
  49. }
  50. func GetProvidersList() []Config {
  51. return configurations
  52. }
  53. func GetProvider(code string) (Config, bool) {
  54. if v, ok := configurationMap[code]; ok {
  55. return v, ok
  56. }
  57. return Config{}, false
  58. }
  59. func (c *Config) SetEnv(configuration Configuration) error {
  60. if c.Configuration != nil {
  61. for k := range c.Configuration.Credentials {
  62. if value, ok := configuration.Credentials[k]; ok {
  63. err := os.Setenv(k, value)
  64. if err != nil {
  65. return err
  66. }
  67. }
  68. }
  69. for k := range c.Configuration.Additional {
  70. if value, ok := configuration.Additional[k]; ok {
  71. err := os.Setenv(k, value)
  72. if err != nil {
  73. return err
  74. }
  75. }
  76. }
  77. }
  78. return nil
  79. }
  80. func (c *Config) CleanEnv() {
  81. if c.Configuration != nil {
  82. for k := range c.Configuration.Credentials {
  83. _ = os.Unsetenv(k)
  84. }
  85. for k := range c.Configuration.Additional {
  86. _ = os.Unsetenv(k)
  87. }
  88. }
  89. }