package server import ( "net/http" "net/http/httputil" "net/url" "os" "strings" ) const adapterGatewayPrefix = "/_/adaptor" func newAdapterGatewayProxy() http.Handler { origin := strings.TrimSpace(os.Getenv("PAGESWIKI_ADAPTER_GATEWAY_ORIGIN")) if origin == "" { origin = "http://adaptor-gateway:3000" } target, err := url.Parse(origin) if err != nil { return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "invalid adapter gateway origin", http.StatusBadGateway) }) } proxy := httputil.NewSingleHostReverseProxy(target) director := proxy.Director proxy.Director = func(request *http.Request) { request.URL.Path = strings.TrimPrefix(request.URL.Path, adapterGatewayPrefix) if request.URL.Path == "" { request.URL.Path = "/" } request.Header.Set("X-Forwarded-Prefix", adapterGatewayPrefix) if request.Header.Get("X-Forwarded-Proto") == "" { if request.TLS != nil { request.Header.Set("X-Forwarded-Proto", "https") } else { request.Header.Set("X-Forwarded-Proto", "http") } } director(request) } return proxy }