From a4a003d9f4566ebfa19d1b72412608d89bd228fa Mon Sep 17 00:00:00 2001 From: Robby Zambito Date: Sat, 1 Feb 2025 20:45:30 -0500 Subject: Add host to subject --- main.go | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index abadcc8..14e75ae 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "io/ioutil" "log" + "net" "net/http" "os" "strings" @@ -90,10 +91,28 @@ func main() { // Create the NATS subject. // Remove the leading slash from the path and replace remaining slashes with dots. - // The subject is prefixed with "http..", where is lower-case. + // The subject is prefixed with "http...", where is lower-case. + + // Extract host and reverse domain components + host := r.Host + // Remove port if present + if h, _, err := net.SplitHostPort(host); err == nil { + host = h + } + // Use "-" instead of "." in the domain to make it a single token. + domainParts := strings.ReplaceAll(host, ".", "-") + + // Process path component path := strings.TrimPrefix(r.URL.Path, "/") subjectPath := strings.ReplaceAll(path, "/", ".") - subject := fmt.Sprintf("http.%s.%s", strings.ToLower(r.Method), subjectPath) + + // Build final subject + subjectBase := "http" + subjectParts := []string{subjectBase, domainParts, strings.ToLower(r.Method)} + if subjectPath != "" { + subjectParts = append(subjectParts, subjectPath) + } + subject := strings.Join(subjectParts, ".") log.Println("Forwarding HTTP", r.Method, "request on", r.URL.Path, "to NATS subject:", subject) @@ -115,6 +134,7 @@ func main() { msg.Header.Set("X-HTTP-Method", r.Method) msg.Header.Set("X-HTTP-Path", r.URL.Path) msg.Header.Set("X-HTTP-Query", r.URL.RawQuery) + msg.Header.Set("X-HTTP-Host", r.Host) msg.Header.Set("X-Remote-Addr", r.RemoteAddr) // Send the NATS request and wait synchronously for a reply (timeout: 30 seconds) -- cgit