Add reverse proxy for local debugging

This commit is contained in:
2021-03-04 17:10:59 +01:00
parent b481db7b45
commit f3f101d804
4 changed files with 89 additions and 53 deletions

View File

@@ -6,6 +6,8 @@ import (
"fmt"
"html/template"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strings"
"time"
@@ -26,11 +28,11 @@ type WebController struct {
hostname string
apiURLInternal string
apiURLExternal string
websiteAddress string
apiURLInternal string
apiURLExternal string
websiteAddress string
sessionCookieDomain string
proxyAPIRequests bool
// page-specific variables
captchaSiteKey string
@@ -55,6 +57,7 @@ func New(
sessionCookieDomain string,
maintenanceMode bool,
debugMode bool,
proxyAPIRequests bool,
) (wc *WebController) {
var err error
wc = &WebController{
@@ -63,6 +66,7 @@ func New(
apiURLExternal: apiURLExternal,
websiteAddress: websiteAddress,
sessionCookieDomain: sessionCookieDomain,
proxyAPIRequests: proxyAPIRequests,
httpClient: &http.Client{Timeout: time.Minute * 10},
api: apiclient.New(apiURLInternal),
}
@@ -96,6 +100,23 @@ func New(
return wc
}
if proxyAPIRequests {
proxPath := strings.TrimSuffix(apiURLInternal, "/api")
proxURL, err := url.Parse(proxPath)
if err != nil {
panic(fmt.Errorf("failed to parse reverse proxy URL '%s': %w", proxPath, err))
}
var prox = httputil.NewSingleHostReverseProxy(proxURL)
prox.Transport = wc.httpClient.Transport
r.Handler("OPTIONS", "/api/*p", prox)
r.Handler("POST", "/api/*p", prox)
r.Handler("GET", "/api/*p", prox)
r.Handler("PUT", "/api/*p", prox)
r.Handler("PATCH", "/api/*p", prox)
r.Handler("DELETE", "/api/*p", prox)
}
r.NotFound = http.HandlerFunc(wc.serveNotFound)
// Request method shorthands. These help keep the array of handlers aligned