proxyRequestHandler.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package dynamicproxy
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "imuslab.com/arozos/mod/network/websocketproxy"
  8. )
  9. func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
  10. var targetProxyEndpoint *ProxyEndpoint = nil
  11. router.ProxyEndpoints.Range(func(key, value interface{}) bool {
  12. rootname := key.(string)
  13. if len(requestURI) >= len(rootname) && requestURI[:len(rootname)] == rootname {
  14. thisProxyEndpoint := value.(*ProxyEndpoint)
  15. targetProxyEndpoint = thisProxyEndpoint
  16. }
  17. return true
  18. })
  19. return targetProxyEndpoint
  20. }
  21. func (router *Router) rewriteURL(rooturl string, requestURL string) string {
  22. if len(requestURL) > len(rooturl) {
  23. return requestURL[len(rooturl):]
  24. }
  25. return ""
  26. }
  27. func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
  28. rewriteURL := h.Parent.rewriteURL(target.Root, r.RequestURI)
  29. fmt.Println("Rewrite URL", rewriteURL)
  30. r.URL, _ = url.Parse(rewriteURL)
  31. r.Header.Set("X-Forwarded-Host", r.Host)
  32. if r.Header["Upgrade"] != nil && r.Header["Upgrade"][0] == "websocket" {
  33. //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
  34. r.Header.Set("A-Upgrade", "websocket")
  35. wsRedirectionEndpoint := target.Domain
  36. if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
  37. wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
  38. }
  39. u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
  40. if target.RequireTLS {
  41. u, _ = url.Parse("wss://localhost:" + wsRedirectionEndpoint + r.URL.String())
  42. }
  43. fmt.Println("WebSocket opening on: " + "ws://" + wsRedirectionEndpoint + r.URL.String())
  44. wspHandler := websocketproxy.NewProxy(u)
  45. wspHandler.ServeHTTP(w, r)
  46. return
  47. }
  48. r.Host = r.URL.Host
  49. err := target.Proxy.ServeHTTP(w, r)
  50. if err != nil {
  51. log.Println(err.Error())
  52. }
  53. }