1
0

config_env.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package dns
  2. import (
  3. "github.com/0xJacky/Nginx-UI/internal/cert/config"
  4. "github.com/BurntSushi/toml"
  5. "log"
  6. "os"
  7. "path/filepath"
  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. files, err := config.DistFS.ReadDir(".")
  27. if err != nil {
  28. log.Fatalln(err)
  29. }
  30. configurationMap = make(map[string]Config)
  31. for _, file := range files {
  32. if filepath.Ext(file.Name()) != ".toml" {
  33. continue
  34. }
  35. c := Config{}
  36. _, err = toml.DecodeFS(config.DistFS, file.Name(), &c)
  37. if err != nil {
  38. log.Fatalln(err)
  39. }
  40. configurationMap[c.Code] = c
  41. c.Configuration = nil
  42. c.Links = nil
  43. configurations = append(configurations, c)
  44. }
  45. }
  46. func GetProvidersList() []Config {
  47. return configurations
  48. }
  49. func GetProvider(code string) (Config, bool) {
  50. if v, ok := configurationMap[code]; ok {
  51. return v, ok
  52. }
  53. return Config{}, false
  54. }
  55. func (c *Config) SetEnv(configuration Configuration) error {
  56. if c.Configuration != nil {
  57. for k := range c.Configuration.Credentials {
  58. if value, ok := configuration.Credentials[k]; ok {
  59. err := os.Setenv(k, value)
  60. if err != nil {
  61. return err
  62. }
  63. }
  64. }
  65. for k := range c.Configuration.Additional {
  66. if value, ok := configuration.Additional[k]; ok {
  67. err := os.Setenv(k, value)
  68. if err != nil {
  69. return err
  70. }
  71. }
  72. }
  73. }
  74. return nil
  75. }
  76. func (c *Config) CleanEnv() {
  77. if c.Configuration != nil {
  78. for k := range c.Configuration.Credentials {
  79. _ = os.Unsetenv(k)
  80. }
  81. for k := range c.Configuration.Additional {
  82. _ = os.Unsetenv(k)
  83. }
  84. }
  85. }