Add host to subject

This commit is contained in:
2025-02-01 20:45:30 -05:00
parent 32c110edfb
commit a4a003d9f4

24
main.go
View File

@@ -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)