Refactor reverse proxy and enhance API routing
- Replaced the existing reverse proxy implementation with a new alias forwarding mechanism, improving path handling and request normalization. - Updated the gateway to utilize the new forwarding approach, ensuring consistent handling of API requests and proper error management. - Enhanced tests to validate the new routing behavior, including handling of double slashes and user endpoint requests. - Improved documentation in GATEWAY_RUN.md to clarify the updated API routing and configuration requirements.
This commit is contained in:
@@ -6,7 +6,6 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -23,7 +22,7 @@ import (
|
||||
// Gateway serves health, metrics, and proxied API routes.
|
||||
type Gateway struct {
|
||||
parsed *config.Parsed
|
||||
proxies map[string]*httputil.ReverseProxy
|
||||
proxies map[string]http.Handler
|
||||
agg *aggregate.Handler
|
||||
geo *geoip.Service
|
||||
log *slog.Logger
|
||||
@@ -44,7 +43,7 @@ func NewGateway(p *config.Parsed, log *slog.Logger, geo *geoip.Service) (*Gatewa
|
||||
t.ResponseHeaderTimeout = 120 * time.Second
|
||||
g := &Gateway{
|
||||
parsed: p,
|
||||
proxies: make(map[string]*httputil.ReverseProxy),
|
||||
proxies: make(map[string]http.Handler),
|
||||
geo: geo,
|
||||
log: log,
|
||||
transport: t,
|
||||
@@ -58,9 +57,7 @@ func NewGateway(p *config.Parsed, log *slog.Logger, geo *geoip.Service) (*Gatewa
|
||||
}
|
||||
auth := p.AuthByAlias[s.Alias]
|
||||
strip := "/api/" + s.Alias
|
||||
rp := proxy.NewReverseProxy(u, strip, s.PathPrefix, auth)
|
||||
rp.Transport = t
|
||||
rp.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
g.proxies[s.Alias] = proxy.NewAliasForward(u, strip, s.PathPrefix, auth, t, func(w http.ResponseWriter, r *http.Request, err error) {
|
||||
log.Error("upstream error", "alias", s.Alias, "err", err)
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
@@ -68,8 +65,7 @@ func NewGateway(p *config.Parsed, log *slog.Logger, geo *geoip.Service) (*Gatewa
|
||||
"ok": false,
|
||||
"error": map[string]string{"code": "bad_gateway", "message": "upstream unreachable"},
|
||||
})
|
||||
}
|
||||
g.proxies[s.Alias] = rp
|
||||
})
|
||||
}
|
||||
var aggCacheTTL time.Duration
|
||||
if p.Config.Aggregate != nil && p.Config.Aggregate.CacheTTLMs > 0 {
|
||||
|
||||
Reference in New Issue
Block a user