redirection.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package redirection
  2. import (
  3. "encoding/json"
  4. "log"
  5. "os"
  6. "path"
  7. "path/filepath"
  8. "strings"
  9. "sync"
  10. "imuslab.com/zoraxy/mod/utils"
  11. )
  12. type RuleTable struct {
  13. configPath string //The location where the redirection rules is stored
  14. rules sync.Map //Store the redirection rules for this reverse proxy instance
  15. }
  16. type RedirectRules struct {
  17. RedirectURL string //The matching URL to redirect
  18. TargetURL string //The destination redirection url
  19. ForwardChildpath bool //Also redirect the pathname
  20. StatusCode int //Status Code for redirection
  21. }
  22. func NewRuleTable(configPath string) (*RuleTable, error) {
  23. thisRuleTable := RuleTable{
  24. rules: sync.Map{},
  25. configPath: configPath,
  26. }
  27. //Load all the rules from the config path
  28. if !utils.FileExists(configPath) {
  29. os.MkdirAll(configPath, 0775)
  30. }
  31. // Load all the *.json from the configPath
  32. files, err := filepath.Glob(filepath.Join(configPath, "*.json"))
  33. if err != nil {
  34. return nil, err
  35. }
  36. // Parse the json content into RedirectRules
  37. var rules []*RedirectRules
  38. for _, file := range files {
  39. b, err := os.ReadFile(file)
  40. if err != nil {
  41. continue
  42. }
  43. thisRule := RedirectRules{}
  44. err = json.Unmarshal(b, &thisRule)
  45. if err != nil {
  46. continue
  47. }
  48. rules = append(rules, &thisRule)
  49. }
  50. //Map the rules into the sync map
  51. for _, rule := range rules {
  52. log.Println("Redirection rule added: " + rule.RedirectURL + " -> " + rule.TargetURL)
  53. thisRuleTable.rules.Store(rule.RedirectURL, rule)
  54. }
  55. return &thisRuleTable, nil
  56. }
  57. func (t *RuleTable) AddRedirectRule(redirectURL string, destURL string, forwardPathname bool, statusCode int) error {
  58. // Create a new RedirectRules object with the given parameters
  59. newRule := &RedirectRules{
  60. RedirectURL: redirectURL,
  61. TargetURL: destURL,
  62. ForwardChildpath: forwardPathname,
  63. StatusCode: statusCode,
  64. }
  65. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  66. filename := strings.ReplaceAll(strings.ReplaceAll(redirectURL, "/", "-"), ".", "_") + ".json"
  67. // Create the full file path by joining the t.configPath with the filename
  68. filepath := path.Join(t.configPath, filename)
  69. // Create a new file for writing the JSON data
  70. file, err := os.Create(filepath)
  71. if err != nil {
  72. log.Printf("Error creating file %s: %s", filepath, err)
  73. return err
  74. }
  75. defer file.Close()
  76. // Encode the RedirectRules object to JSON and write it to the file
  77. err = json.NewEncoder(file).Encode(newRule)
  78. if err != nil {
  79. log.Printf("Error encoding JSON to file %s: %s", filepath, err)
  80. return err
  81. }
  82. // Store the RedirectRules object in the sync.Map
  83. t.rules.Store(redirectURL, newRule)
  84. return nil
  85. }
  86. func (t *RuleTable) DeleteRedirectRule(redirectURL string) error {
  87. // Convert the redirectURL to a valid filename by replacing "/" with "-" and "." with "_"
  88. filename := strings.ReplaceAll(strings.ReplaceAll(redirectURL, "/", "-"), ".", "_") + ".json"
  89. // Create the full file path by joining the t.configPath with the filename
  90. filepath := path.Join(t.configPath, filename)
  91. // Check if the file exists
  92. if _, err := os.Stat(filepath); os.IsNotExist(err) {
  93. return nil // File doesn't exist, nothing to delete
  94. }
  95. // Delete the file
  96. if err := os.Remove(filepath); err != nil {
  97. log.Printf("Error deleting file %s: %s", filepath, err)
  98. return err
  99. }
  100. // Delete the key-value pair from the sync.Map
  101. t.rules.Delete(redirectURL)
  102. return nil
  103. }
  104. // Get a list of all the redirection rules
  105. func (t *RuleTable) GetAllRedirectRules() []*RedirectRules {
  106. rules := []*RedirectRules{}
  107. t.rules.Range(func(key, value interface{}) bool {
  108. r, ok := value.(*RedirectRules)
  109. if ok {
  110. rules = append(rules, r)
  111. }
  112. return true
  113. })
  114. return rules
  115. }
  116. // Check if a given request URL matched any of the redirection rule
  117. func (t *RuleTable) MatchRedirectRule(requestedURL string) *RedirectRules {
  118. // Iterate through all the keys in the rules map
  119. var targetRedirectionRule *RedirectRules = nil
  120. var maxMatch int = 0
  121. t.rules.Range(func(key interface{}, value interface{}) bool {
  122. // Check if the requested URL starts with the key as a prefix
  123. if strings.HasPrefix(requestedURL, key.(string)) {
  124. // This request URL matched the domain
  125. if len(key.(string)) > maxMatch {
  126. maxMatch = len(key.(string))
  127. targetRedirectionRule = value.(*RedirectRules)
  128. }
  129. }
  130. return true
  131. })
  132. return targetRedirectionRule
  133. }