Server.go 2.4 KB

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