config.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package main
  2. import (
  3. "encoding/json"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "imuslab.com/zoraxy/mod/utils"
  10. )
  11. /*
  12. Reverse Proxy Configs
  13. The following section handle
  14. the reverse proxy configs
  15. */
  16. type Record struct {
  17. ProxyType string
  18. Rootname string
  19. ProxyTarget string
  20. UseTLS bool
  21. }
  22. func SaveReverseProxyConfig(ptype string, rootname string, proxyTarget string, useTLS bool) error {
  23. //TODO: Make this accept new def types
  24. os.MkdirAll("conf", 0775)
  25. filename := getFilenameFromRootName(rootname)
  26. //Generate record
  27. thisRecord := Record{
  28. ProxyType: ptype,
  29. Rootname: rootname,
  30. ProxyTarget: proxyTarget,
  31. UseTLS: useTLS,
  32. }
  33. //Write to file
  34. js, _ := json.MarshalIndent(thisRecord, "", " ")
  35. return ioutil.WriteFile(filepath.Join("conf", filename), js, 0775)
  36. }
  37. func RemoveReverseProxyConfig(rootname string) error {
  38. filename := getFilenameFromRootName(rootname)
  39. removePendingFile := strings.ReplaceAll(filepath.Join("conf", filename), "\\", "/")
  40. log.Println("Config Removed: ", removePendingFile)
  41. if utils.FileExists(removePendingFile) {
  42. err := os.Remove(removePendingFile)
  43. if err != nil {
  44. log.Println(err.Error())
  45. return err
  46. }
  47. }
  48. //File already gone
  49. return nil
  50. }
  51. // Return ptype, rootname and proxyTarget, error if any
  52. func LoadReverseProxyConfig(filename string) (*Record, error) {
  53. thisRecord := Record{}
  54. configContent, err := ioutil.ReadFile(filename)
  55. if err != nil {
  56. return &thisRecord, err
  57. }
  58. //Unmarshal the content into config
  59. err = json.Unmarshal(configContent, &thisRecord)
  60. if err != nil {
  61. return &thisRecord, err
  62. }
  63. //Return it
  64. return &thisRecord, nil
  65. }
  66. func getFilenameFromRootName(rootname string) string {
  67. //Generate a filename for this rootname
  68. filename := strings.ReplaceAll(rootname, ".", "_")
  69. filename = strings.ReplaceAll(filename, "/", "-")
  70. filename = filename + ".config"
  71. return filename
  72. }