mirror of
https://git.robbyzambito.me/http-nats-proxy
synced 2025-12-21 08:44:50 +00:00
Update endpoint -> subject encoding
Use an encoding that can be safely used bidirectionally while still being easy to read. This is useful for being able to make HTTP requests from NATS, which I am working on now.
This commit is contained in:
33
main.go
33
main.go
@@ -7,6 +7,7 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -29,6 +30,27 @@ func printHelp() {
|
|||||||
fmt.Println(" HTTP_PORT - HTTP port to listen on (default: 8080)")
|
fmt.Println(" HTTP_PORT - HTTP port to listen on (default: 8080)")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// URL to NATS subject conversion
|
||||||
|
func URLToNATS(urlPath string) (string, error) {
|
||||||
|
segments := strings.Split(strings.Trim(urlPath, "/"), "/")
|
||||||
|
for i, seg := range segments {
|
||||||
|
// Decode existing encoding first to prevent double-encoding
|
||||||
|
unescaped, err := url.PathUnescape(seg)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("failed to unescape segment: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode special NATS-sensitive characters
|
||||||
|
encoded := url.PathEscape(unescaped)
|
||||||
|
encoded = strings.ReplaceAll(encoded, ".", "%2E") // Critical for token separation
|
||||||
|
encoded = strings.ReplaceAll(encoded, "*", "%2A") // Wildcard protection
|
||||||
|
encoded = strings.ReplaceAll(encoded, ">", "%3E") // Wildcard protection
|
||||||
|
|
||||||
|
segments[i] = encoded
|
||||||
|
}
|
||||||
|
return strings.Join(segments, "."), nil
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
helpFlag := flag.Bool("help", false, "Display help information about available environment variables")
|
helpFlag := flag.Bool("help", false, "Display help information about available environment variables")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
@@ -103,9 +125,14 @@ func main() {
|
|||||||
domainParts := strings.ReplaceAll(host, ".", "_")
|
domainParts := strings.ReplaceAll(host, ".", "_")
|
||||||
|
|
||||||
// Process path component
|
// Process path component
|
||||||
path := strings.TrimPrefix(r.URL.Path, "/")
|
path := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/"), "/")
|
||||||
// Replace all "." with "_" and then all "/" with ".".
|
subjectPath, err := URLToNATS(path)
|
||||||
subjectPath := strings.ReplaceAll(strings.ReplaceAll(path, ".", "_"), "/", ".")
|
if err != nil {
|
||||||
|
http.Error(w, "Error converting endpoint to NATS subject", http.StatusInternalServerError)
|
||||||
|
log.Println("Could not convert endpoint to NATS subject", err)
|
||||||
|
return
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
// Build final subject
|
// Build final subject
|
||||||
subjectBase := "http"
|
subjectBase := "http"
|
||||||
|
|||||||
Reference in New Issue
Block a user