package main import ( "context" "log" "net/http" "os" "time" "github.com/chedius/delivery-tracker/internal/auth" db "github.com/chedius/delivery-tracker/internal/db/sqlc" "github.com/chedius/delivery-tracker/internal/delivery" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "github.com/jackc/pgx/v5/pgxpool" "github.com/joho/godotenv" ) func initAuth(queries *db.Queries) (*auth.Service, *auth.Handler) { secret := []byte(os.Getenv("JWT_SECRET")) expiry := 24 * time.Hour if len(secret) == 0 { log.Fatal("JWT_SECRET not set") } service := auth.New(queries, secret, expiry) handler := auth.NewHandler(service) return service, handler } func main() { ctx := context.Background() godotenv.Load() dsn := os.Getenv("DATABASE_URL") pool, err := pgxpool.New(ctx, dsn) if err != nil { log.Fatalf("db connect: %v", err) } defer pool.Close() queries := db.New(pool) _, authHandler := initAuth(queries) h := delivery.NewHandler(queries) r := gin.Default() // CORS middleware - allow all origins in development r.Use(cors.New(cors.Config{ AllowOrigins: []string{"*"}, AllowMethods: []string{"GET", "POST", "PATCH", "PUT", "DELETE", "OPTIONS"}, AllowHeaders: []string{"*"}, AllowCredentials: false, MaxAge: 12 * time.Hour, })) r.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) }) r.POST("/api/auth/register", authHandler.Register) r.POST("/api/auth/login", authHandler.Login) authorized := r.Group("/api") authorized.Use(auth.AuthMiddleware([]byte(os.Getenv("JWT_SECRET")))) { authorized.GET("/deliveries", h.GetDeliveries) authorized.GET("/deliveries/:id", h.GetDeliveryByID) authorized.GET("/deliveries/count", h.GetDeliveryCount) authorized.POST("/deliveries", h.CreateDelivery) authorized.PATCH("/deliveries/:id", h.UpdateDelivery) authorized.PATCH("/deliveries/:id/status", h.UpdateDeliveryStatus) authorized.DELETE("/deliveries/:id", h.DeleteDelivery) } r.Run(":8080") }