diff options
Diffstat (limited to 'main.go')
-rw-r--r-- | main.go | 51 |
1 files changed, 48 insertions, 3 deletions
@@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "flag" "fmt" "log" "log/slog" @@ -18,11 +19,55 @@ import ( "github.com/nats-io/nats.go" ) +// printHelp outputs the usage information. +func printHelp() { + fmt.Println("Usage: HTTP-to-NATS proxy server") + fmt.Println("\nThe following environment variables are supported:") + fmt.Println(" NATS_URL - NATS connection URL (default: nats://127.0.0.1:4222)") + fmt.Println(" NATS_USER - NATS username for authentication (optional)") + fmt.Println(" NATS_PASSWORD - NATS password for authentication (optional)") + fmt.Println(" NATS_TOKEN - NATS token for authentication (optional)") + fmt.Println(" NATS_NKEY - NATS NKEY for authentication (optional)") + fmt.Println(" NATS_NKEY_SEED - NATS NKEY seed for authentication (optional)") + fmt.Println(" NATS_CREDS_FILE - Path to NATS credentials file (optional)") +} + func main() { - // Connect to NATS - nc, err := nats.Connect(nats.DefaultURL) + helpFlag := flag.Bool("help", false, "Display help information about available environment variables") + flag.Parse() + if *helpFlag { + printHelp() + os.Exit(0) + } + + // Read NATS connection info from environment variables + natsURL := os.Getenv("NATS_URL") + if natsURL == "" { + natsURL = nats.DefaultURL // defaults to "nats://127.0.0.1:4222" + } + natsUser := os.Getenv("NATS_USER") + natsPassword := os.Getenv("NATS_PASSWORD") + natsToken := os.Getenv("NATS_TOKEN") + natsNkey := os.Getenv("NATS_NKEY") + natsNkeySeed := os.Getenv("NATS_NKEY_SEED") + natsCredsFile := os.Getenv("NATS_CREDS_FILE") + + // Set up NATS connection options + opts := []nats.Option{nats.Name("Web proxy")} + + if natsUser != "" && natsPassword != "" { + opts = append(opts, nats.UserInfo(natsUser, natsPassword)) + } else if natsToken != "" { + opts = append(opts, nats.Token(natsToken)) + } else if natsNkey != "" && natsNkeySeed != "" { + log.Fatalln("NKEY connection not supported") + } else if natsCredsFile != "" { + opts = append(opts, nats.UserCredentials(natsCredsFile)) + } + + nc, err := nats.Connect(natsURL, opts...) if err != nil { - log.Fatalf("Error connecting to NATS: %v", err) + log.Fatal("Error connecting to NATS:", err) } defer nc.Close() log.Println("Connected to NATS") |