config.go 1.9 KB

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