diff options
author | Robby Zambito <contact@robbyzambito.me> | 2025-02-01 20:45:30 -0500 |
---|---|---|
committer | Robby Zambito <contact@robbyzambito.me> | 2025-02-09 17:06:31 -0500 |
commit | a4a003d9f4566ebfa19d1b72412608d89bd228fa (patch) | |
tree | 0b02de64430dbcd1d7eb6dd19c4c36e592c4f7b7 | |
parent | 32c110edfb97abce50ed1d57e529cb7eda2428dd (diff) |
Add host to subject
-rw-r--r-- | main.go | 24 |
1 files changed, 22 insertions, 2 deletions
@@ -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.<method>.", where <method> is lower-case. + // The subject is prefixed with "http.<host>.<method>.", where <method> 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) |