diff options
| author | Leonardo Bishop <me@leonardobishop.com> | 2025-02-06 15:22:34 +0000 |
|---|---|---|
| committer | Leonardo Bishop <me@leonardobishop.com> | 2025-02-06 15:22:34 +0000 |
| commit | 2475f5a8b92ef0dd28e7af5f36d01b25243ed778 (patch) | |
| tree | 12f8931d241db4159f8d30f7bf2b648709a94166 /api/handlers/reverseProxy.go | |
Initial commit
Diffstat (limited to 'api/handlers/reverseProxy.go')
| -rw-r--r-- | api/handlers/reverseProxy.go | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/api/handlers/reverseProxy.go b/api/handlers/reverseProxy.go new file mode 100644 index 0000000..4ac4c87 --- /dev/null +++ b/api/handlers/reverseProxy.go @@ -0,0 +1,35 @@ +package handlers + +import ( + "fmt" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "time" + + "github.com/LMBishop/gunnel/pkg/store" +) + +func ReverseProxy(storeService store.Service) func(http.ResponseWriter, *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + hostParts := strings.Split(r.Host, ".") + + slug := hostParts[0] + rule := storeService.GetRuleBySlug(slug) + if rule == nil { + http.Error(w, fmt.Sprintf("Unknown peer '%s'", slug), http.StatusNotFound) + return + } + + targetURL, err := url.Parse("http://" + rule.Peer.IPAddr.String() + ":" + rule.Port) + rule.LastUsed = time.Now() + if err != nil { + http.Error(w, "Invalid target URL", http.StatusInternalServerError) + return + } + + proxy := httputil.NewSingleHostReverseProxy(targetURL) + proxy.ServeHTTP(w, r) + } +} |
