diff options
author | Robby Zambito <contact@robbyzambito.me> | 2025-01-21 20:36:07 -0500 |
---|---|---|
committer | Robby Zambito <contact@robbyzambito.me> | 2025-02-01 11:03:44 -0500 |
commit | cdb221b7523cc3a0fbebc28b40176642027c7f83 (patch) | |
tree | b4b48037e2cbb0f920eca4c2aaef290b346835ad /main.go |
Initial commit
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 72 |
1 files changed, 72 insertions, 0 deletions
@@ -0,0 +1,72 @@ +package main + +import ( + "fmt" + "io/ioutil" + "log" + "net/http" + "strings" + "time" + + "github.com/nats-io/nats.go" +) + +func main() { + // Connect to NATS server + nc, err := nats.Connect(nats.DefaultURL) + if err != nil { + log.Fatal(err) + } + defer nc.Close() + + // HTTP handler function + http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + // Read the request body + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error reading request body", http.StatusInternalServerError) + return + } + defer r.Body.Close() + + // Drop the leading slash if there is one, and replace slashes with dots. + subject := strings.ReplaceAll(strings.TrimPrefix(r.URL.Path, "/"), "/", ".") + + // Create a NATS message with the request body and headers + msg := nats.Msg{ + Subject: fmt.Sprintf("http.%s", subject), + Data: body, + Header: nats.Header{}, + } + log.Println("subject:", msg.Subject) + + // Copy HTTP headers to NATS message headers + for key, values := range r.Header { + for _, value := range values { + msg.Header.Add(key, value) + } + } + + // Send request to NATS and wait for reply + reply, err := nc.RequestMsg(&msg, 30*time.Second) + if err != nil { + http.Error(w, "Error processing request", http.StatusInternalServerError) + log.Println("Error processing the request", err) + return + } + + // Copy NATS reply headers to HTTP response + for key, values := range reply.Header { + for _, value := range values { + w.Header().Add(key, value) + } + } + + // Write NATS reply body to HTTP response + w.Write(reply.Data) + }) + + // Start HTTP server + fmt.Println("Server is running on http://localhost:8080") + log.Fatal(http.ListenAndServe(":8080", nil)) +} |