123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- package dynamicproxy
- import (
- "fmt"
- "log"
- "net/http"
- "net/url"
- "imuslab.com/arozos/mod/network/websocketproxy"
- )
- func (router *Router) getTargetProxyEndpointFromRequestURI(requestURI string) *ProxyEndpoint {
- var targetProxyEndpoint *ProxyEndpoint = nil
- router.ProxyEndpoints.Range(func(key, value interface{}) bool {
- rootname := key.(string)
- if len(requestURI) >= len(rootname) && requestURI[:len(rootname)] == rootname {
- thisProxyEndpoint := value.(*ProxyEndpoint)
- targetProxyEndpoint = thisProxyEndpoint
- }
- return true
- })
- return targetProxyEndpoint
- }
- func (router *Router) rewriteURL(rooturl string, requestURL string) string {
- if len(requestURL) > len(rooturl) {
- return requestURL[len(rooturl):]
- }
- return ""
- }
- func (h *ProxyHandler) proxyRequest(w http.ResponseWriter, r *http.Request, target *ProxyEndpoint) {
- rewriteURL := h.Parent.rewriteURL(target.Root, r.RequestURI)
- fmt.Println("Rewrite URL", rewriteURL)
- r.URL, _ = url.Parse(rewriteURL)
- r.Header.Set("X-Forwarded-Host", r.Host)
- if r.Header["Upgrade"] != nil && r.Header["Upgrade"][0] == "websocket" {
- //Handle WebSocket request. Forward the custom Upgrade header and rewrite origin
- r.Header.Set("A-Upgrade", "websocket")
- wsRedirectionEndpoint := target.Domain
- if wsRedirectionEndpoint[len(wsRedirectionEndpoint)-1:] != "/" {
- wsRedirectionEndpoint = wsRedirectionEndpoint + "/"
- }
- u, _ := url.Parse("ws://" + wsRedirectionEndpoint + r.URL.String())
- if target.RequireTLS {
- u, _ = url.Parse("wss://localhost:" + wsRedirectionEndpoint + r.URL.String())
- }
- fmt.Println("WebSocket opening on: " + "ws://" + wsRedirectionEndpoint + r.URL.String())
- wspHandler := websocketproxy.NewProxy(u)
- wspHandler.ServeHTTP(w, r)
- return
- }
- r.Host = r.URL.Host
- err := target.Proxy.ServeHTTP(w, r)
- if err != nil {
- log.Println(err.Error())
- }
- }
|