From d5b34a9f827e51cc29397691716a27d52fd782d8 Mon Sep 17 00:00:00 2001 From: "corrado.mulas" Date: Wed, 20 Nov 2024 00:51:56 +0100 Subject: [PATCH] First commit --- handlers.go | 9 --------- main.go | 28 +++++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/handlers.go b/handlers.go index 8492fdc..38ecde3 100644 --- a/handlers.go +++ b/handlers.go @@ -3,12 +3,9 @@ package main import ( "encoding/json" "fmt" - "log" "net/http" "os" "strings" - - "github.com/joho/godotenv" ) // RegistrationRequest represents the incoming registration request. @@ -112,9 +109,3 @@ func validateEnvVars(vars []string) error { } return nil } - -func loadEnv() { - if err := godotenv.Load(); err != nil { - log.Println("No .env file found, using system environment variables") - } -} diff --git a/main.go b/main.go index ff5db1a..8ea335b 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,8 @@ import ( "os" "github.com/joho/godotenv" + + "github.com/rs/cors" ) func loadEnv() { @@ -18,13 +20,33 @@ func main() { // Load environment variables loadEnv() - http.HandleFunc("/register", registerHandler) + // Validate required environment variables + requiredVars := []string{"ALLOWED_DOMAINS", "CAPTCHA_SERVER_KEY", "OL_INSTANCE", "OL_ADMIN_EMAIL", "OL_ADMIN_PASSWORD"} + if err := validateEnvVars(requiredVars); err != nil { + log.Fatalf("Environment validation failed: %v", err) + } + // Set up HTTP routes + mux := http.NewServeMux() + mux.HandleFunc("/register", registerHandler) + + // Apply CORS middleware + c := cors.New(cors.Options{ + AllowedOrigins: []string{"*"}, // Replace "*" with specific frontend origins, if needed + AllowedMethods: []string{"GET", "POST", "OPTIONS"}, + AllowedHeaders: []string{"Content-Type", "Authorization"}, + AllowCredentials: true, + }) + + // Wrap your handler with CORS middleware + handler := c.Handler(mux) + + // Start the server port := os.Getenv("PORT") if port == "" { - port = "3000" // Default to port 3000 + port = "3000" } log.Printf("Starting server on port %s...", port) - log.Fatal(http.ListenAndServe(":"+port, nil)) + log.Fatal(http.ListenAndServe(":"+port, handler)) }