Skip to content

Commit 5d352b7

Browse files
committed
Add UpstreamHostOverride support for plugins and enhance reverse proxy handling
- Introduced UpstreamHostOverride constant in ctx package for plugin use. - Implemented logic in reverse_proxy.go to allow plugins to override upstream host or URL. - Added a new test file for URL redirect plugin to demonstrate UpstreamHostOverride functionality.
1 parent 00b0a31 commit 5d352b7

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

ctx/ctx.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@ const (
5353
CacheOptions
5454
OASDefinition
5555
SelfLooping
56+
// Used by plugins to override the upstream host
57+
UpstreamHostOverride
5658
)
5759

5860
func ctxSetSession(r *http.Request, s *user.SessionState, scheduleUpdate bool, hashKey bool) {

gateway/reverse_proxy.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,8 +293,27 @@ func (gw *Gateway) TykNewSingleHostReverseProxy(target *url.URL, spec *APISpec,
293293
}
294294
}
295295

296+
// Simple upstream host override from plugins via context.
297+
// Accepts either a host (e.g. "api.example.com") or full URL (e.g. "https://api.example.com").
298+
if v := req.Context().Value(ctx.UpstreamHostOverride); v != nil {
299+
if hostOrURL, ok := v.(string); ok && hostOrURL != "" {
300+
if strings.Contains(hostOrURL, "://") {
301+
if u, err := url.Parse(hostOrURL); err == nil {
302+
if u.Scheme != "" {
303+
req.URL.Scheme = u.Scheme
304+
}
305+
if u.Host != "" {
306+
req.URL.Host = u.Host
307+
}
308+
}
309+
} else {
310+
req.URL.Host = hostOrURL
311+
}
312+
}
313+
}
314+
296315
if !spec.Proxy.PreserveHostHeader {
297-
req.Host = targetToUse.Host
316+
req.Host = req.URL.Host
298317
}
299318

300319
if targetQuery == "" || req.URL.RawQuery == "" {

test/goplugins/url_redirect_plugin.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package main
2+
3+
import (
4+
"context"
5+
"net/http"
6+
7+
"github.com/TykTechnologies/tyk/ctx"
8+
"github.com/TykTechnologies/tyk/log"
9+
)
10+
11+
var logger = log.Get()
12+
13+
func HeaderBasedRedirect(rw http.ResponseWriter, r *http.Request) {
14+
routeTo := r.Header.Get("X-Route-To")
15+
if routeTo == "" {
16+
return
17+
}
18+
19+
logger.Info("[PLUGIN] X-Route-To header: ", routeTo)
20+
21+
// Use the UpstreamHostOverride context key
22+
// This can be either a host or a full URL
23+
newCtx := context.WithValue(r.Context(), ctx.UpstreamHostOverride, routeTo)
24+
*r = *r.WithContext(newCtx)
25+
26+
logger.Info("[PLUGIN] Set UpstreamHostOverride to: ", routeTo)
27+
}
28+
29+
func main() {}

0 commit comments

Comments
 (0)