Server.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. //Extract request host to see if it is virtual directory or subdomain
  34. domainOnly := r.Host
  35. if strings.Contains(r.Host, ":") {
  36. hostPath := strings.Split(r.Host, ":")
  37. domainOnly = hostPath[0]
  38. }
  39. if strings.Contains(r.Host, ".") {
  40. //This might be a subdomain. See if there are any subdomain proxy router for this
  41. //Remove the port if any
  42. sep := h.Parent.getSubdomainProxyEndpointFromHostname(domainOnly)
  43. if sep != nil {
  44. h.subdomainRequest(w, r, sep)
  45. return
  46. }
  47. }
  48. //Clean up the request URI
  49. proxyingPath := strings.TrimSpace(r.RequestURI)
  50. targetProxyEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath)
  51. if targetProxyEndpoint != nil {
  52. h.proxyRequest(w, r, targetProxyEndpoint)
  53. } else if !strings.HasSuffix(proxyingPath, "/") {
  54. potentialProxtEndpoint := h.Parent.getTargetProxyEndpointFromRequestURI(proxyingPath + "/")
  55. if potentialProxtEndpoint != nil {
  56. h.proxyRequest(w, r, potentialProxtEndpoint)
  57. } else {
  58. h.proxyRequest(w, r, h.Parent.Root)
  59. }
  60. } else {
  61. h.proxyRequest(w, r, h.Parent.Root)
  62. }
  63. }