config.go 1.7 KB

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