package main import ( "fmt" "log" "net/http" "os" "regexp" "shop.tonybtw.com/internal/handlers" "shop.tonybtw.com/internal/lib" ) type Route struct { method string pattern *regexp.Regexp handler http.HandlerFunc } func main() { db, err := lib.Connect_DB() if err != nil { log.Fatal("Failed to connect to database:", err) } defer db.Close() ctx := lib.New_App_Context(db) shop_handler := handlers.New_Shop_Handler(ctx) cart_handler := handlers.New_Cart_Handler(ctx) checkout_handler := handlers.New_Checkout_Handler(ctx) webhook_handler := handlers.New_Webhook_Handler(ctx) routes := []Route{ { method: "GET", pattern: regexp.MustCompile(`^/$`), handler: shop_handler.Show_Home, }, { method: "GET", pattern: regexp.MustCompile(`^/product/([^/]+)$`), handler: func(w http.ResponseWriter, r *http.Request) { matches := regexp.MustCompile(`^/product/([^/]+)$`).FindStringSubmatch(r.URL.Path) if len(matches) > 1 { shop_handler.Show_Product(w, r, matches[1]) } }, }, { method: "GET", pattern: regexp.MustCompile(`^/cart$`), handler: cart_handler.Show_Cart, }, { method: "POST", pattern: regexp.MustCompile(`^/cart/add$`), handler: cart_handler.Add_Item, }, { method: "POST", pattern: regexp.MustCompile(`^/cart/update$`), handler: cart_handler.Update_Item, }, { method: "POST", pattern: regexp.MustCompile(`^/cart/remove$`), handler: cart_handler.Remove_Item, }, { method: "GET", pattern: regexp.MustCompile(`^/checkout$`), handler: checkout_handler.Show_Checkout, }, { method: "POST", pattern: regexp.MustCompile(`^/checkout/create$`), handler: lib.Require_CSRF(checkout_handler.Create_Session), }, { method: "GET", pattern: regexp.MustCompile(`^/success$`), handler: checkout_handler.Show_Success, }, { method: "POST", pattern: regexp.MustCompile(`^/webhook/stripe$`), handler: webhook_handler.Handle_Stripe, }, } http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("public/static")))) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { for _, route := range routes { if r.Method == route.method && route.pattern.MatchString(r.URL.Path) { route.handler(w, r) return } } http.NotFound(w, r) }) port := os.Getenv("PORT") if port == "" { port = "8080" } fmt.Printf("Server starting on http://localhost:%s\n", port) if err := http.ListenAndServe(":"+port, nil); err != nil { log.Fatal(err) } }