providerutils.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package acmedns
  2. import (
  3. _ "embed"
  4. "encoding/json"
  5. "errors"
  6. "net/http"
  7. "imuslab.com/zoraxy/mod/utils"
  8. )
  9. //go:embed providers.json
  10. var providers []byte //A list of providers generated by acmedns code-generator
  11. type ConfigTemplate struct {
  12. Name string `json:"Name"`
  13. ConfigableFields []struct {
  14. Title string `json:"Title"`
  15. Datatype string `json:"Datatype"`
  16. } `json:"ConfigableFields"`
  17. HiddenFields []struct {
  18. Title string `json:"Title"`
  19. Datatype string `json:"Datatype"`
  20. } `json:"HiddenFields"`
  21. }
  22. // Return a map of string => datatype
  23. func GetProviderConfigStructure(providerName string) (map[string]string, error) {
  24. //Load the target config template from embedded providers.json
  25. configTemplateMap := map[string]ConfigTemplate{}
  26. err := json.Unmarshal(providers, &configTemplateMap)
  27. if err != nil {
  28. return map[string]string{}, err
  29. }
  30. targetConfigTemplate, ok := configTemplateMap[providerName]
  31. if !ok {
  32. return map[string]string{}, errors.New("provider not supported")
  33. }
  34. results := map[string]string{}
  35. for _, field := range targetConfigTemplate.ConfigableFields {
  36. results[field.Title] = field.Datatype
  37. }
  38. return results, nil
  39. }
  40. // HandleServeProvidersJson return the list of supported providers as json
  41. func HandleServeProvidersJson(w http.ResponseWriter, r *http.Request) {
  42. providerName, _ := utils.GetPara(r, "name")
  43. if providerName == "" {
  44. //Send the current list of providers
  45. configTemplateMap := map[string]ConfigTemplate{}
  46. err := json.Unmarshal(providers, &configTemplateMap)
  47. if err != nil {
  48. utils.SendErrorResponse(w, "failed to load DNS provider")
  49. return
  50. }
  51. //Parse the provider names into an array
  52. providers := []string{}
  53. for providerName, _ := range configTemplateMap {
  54. providers = append(providers, providerName)
  55. }
  56. js, _ := json.Marshal(providers)
  57. utils.SendJSONResponse(w, string(js))
  58. return
  59. }
  60. //Get the config for that provider
  61. confTemplate, err := GetProviderConfigStructure(providerName)
  62. if err != nil {
  63. utils.SendErrorResponse(w, err.Error())
  64. return
  65. }
  66. js, _ := json.Marshal(confTemplate)
  67. utils.SendJSONResponse(w, string(js))
  68. }