acme_dns.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package acme
  2. import (
  3. "errors"
  4. "log"
  5. "os"
  6. "strings"
  7. "github.com/go-acme/lego/v4/challenge"
  8. "github.com/go-acme/lego/v4/providers/dns"
  9. )
  10. func GetDnsChallengeProviderByName(dnsProvider string, dnsCredentials string) (challenge.Provider, error) {
  11. credentials, err := extractDnsCredentials(dnsCredentials)
  12. if err != nil {
  13. return nil, err
  14. }
  15. setCredentialsIntoEnvironmentVariables(credentials)
  16. provider, err := dns.NewDNSChallengeProviderByName(dnsProvider)
  17. return provider, err
  18. }
  19. func setCredentialsIntoEnvironmentVariables(credentials map[string]string) {
  20. for key, value := range credentials {
  21. err := os.Setenv(key, value)
  22. if err != nil {
  23. log.Println("[ERR] Failed to set environment variable %s: %v", key, err)
  24. } else {
  25. log.Println("[INFO] Environment variable %s set successfully", key)
  26. }
  27. }
  28. }
  29. func extractDnsCredentials(input string) (map[string]string, error) {
  30. result := make(map[string]string)
  31. // Split the input string by newline character
  32. lines := strings.Split(input, "\n")
  33. // Iterate over each line
  34. for _, line := range lines {
  35. // Split the line by "=" character
  36. //use SpliyN to make sure not to split the value if the value is base64
  37. parts := strings.SplitN(line, "=", 1)
  38. // Check if the line is in the correct format
  39. if len(parts) == 2 {
  40. key := strings.TrimSpace(parts[0])
  41. value := strings.TrimSpace(parts[1])
  42. // Add the key-value pair to the map
  43. result[key] = value
  44. if value == "" || key == "" {
  45. //invalid config
  46. return result, errors.New("DNS credential extract failed")
  47. }
  48. }
  49. }
  50. return result, nil
  51. }