Server.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package dynamicproxy
  2. import (
  3. "fmt"
  4. "net/http"
  5. "os"
  6. "strings"
  7. "imuslab.com/zoraxy/mod/geodb"
  8. )
  9. /*
  10. Server.go
  11. Main server for dynamic proxy core
  12. */
  13. func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  14. //Check if this ip is in blacklist
  15. clientIpAddr := geodb.GetRequesterIP(r)
  16. if h.Parent.Option.GeodbStore.IsBlacklisted(clientIpAddr) {
  17. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  18. w.WriteHeader(http.StatusForbidden)
  19. template, err := os.ReadFile("./web/forbidden.html")
  20. if err != nil {
  21. w.Write([]byte("403 - Forbidden"))
  22. } else {
  23. w.Write(template)
  24. }
  25. h.logRequest(r, false, 403, "blacklist")
  26. return
  27. }
  28. //Check if this is a redirection url
  29. if h.Parent.Option.RedirectRuleTable.IsRedirectable(r) {
  30. statusCode := h.Parent.Option.RedirectRuleTable.HandleRedirect(w, r)
  31. h.logRequest(r, statusCode != 500, statusCode, "redirect")
  32. return
  33. }
  34. //Check if there are external routing rule matches.
  35. //If yes, route them via external rr
  36. matchedRoutingRule := h.Parent.GetMatchingRoutingRule(r)
  37. if matchedRoutingRule != nil {
  38. //Matching routing rule found. Let the sub-router handle it
  39. matchedRoutingRule.Route(w, r)
  40. return
  41. }
  42. //Extract request host to see if it is virtual directory or subdomain
  43. domainOnly := r.Host
  44. if strings.Contains(r.Host, ":") {
  45. hostPath := strings.Split(r.Host, ":")
  46. domainOnly = hostPath[0]
  47. }
  48. if strings.Contains(r.Host, ".") {
  49. //This might be a subdomain. See if there are any subdomain proxy router for this
  50. //Remove the port if any
  51. sep := h.Parent.getSubdomainProxyEndpointFromHostname(domainOnly)
  52. if sep != nil {
  53. h.subdomainRequest(w, r, sep)
  54. return
  55. }
  56. }
  57. //Clean up the request URI
  58. proxyingPath := strings.TrimSpace(r.RequestURI)
  59. targetProxyEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath)
  60. if targetProxyEndpoint != nil {
  61. h.proxyRequest(w, r, targetProxyEndpoint)
  62. } else if !strings.HasSuffix(proxyingPath, "/") {
  63. potentialProxtEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath + "/")
  64. if potentialProxtEndpoint != nil {
  65. //Missing tailing slash. Redirect to target proxy endpoint
  66. fmt.Println("Missing back slash. Redirecting to " + r.RequestURI + "/")
  67. http.Redirect(w, r, r.RequestURI+"/", http.StatusTemporaryRedirect)
  68. //h.proxyRequest(w, r, potentialProxtEndpoint)
  69. } else {
  70. h.proxyRequest(w, r, h.Parent.Root)
  71. }
  72. } else {
  73. h.proxyRequest(w, r, h.Parent.Root)
  74. }
  75. }