package controllers import ( "log" "fmt" "os" "time" "net/http" "encoding/json" "github.com/gorilla/mux" "github.com/joho/godotenv" "gorm.io/driver/postgres" "gorm.io/gorm" ) // User represents a user in the system type User struct { UserID uint `gorm:"primaryKey"` Username string `gorm:"size:50;not null"` Email string `gorm:"size:100;not null"` Password string `gorm:"size:100;not null"` CreatedAt time.Time `gorm:"autoCreateTime"` } // GetUsers handles the GET /users route func GetUsers(w http.ResponseWriter, r *http.Request) { users := []User{ {UserID: 1, Username: "John Doe"}, {UserID: 2, Username: "Jane Doe"}, } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(users) } // GetUser handles the GET /users/{id} route func GetUser(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] user := User{UserID: 1, Username: "John Doe"} // Placeholder user if id == "1" { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(user) } else { http.Error(w, "User not found", http.StatusNotFound) } } // CreateUser handles the POST /users route func CreateUser(w http.ResponseWriter, r *http.Request) { user := User{Username: "john_doe", Email: "john@example.com", Password: "securepassword"} err := json.NewDecoder(r.Body).Decode(&user) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } db, err:=connector() // Auto-migrate the schema db.AutoMigrate(&User{}) // Example of inserting a user db.Create(&user) // At this point, user.UserID will be set to the ID generated by the database log.Println("New user ID:", user.UserID) fmt.Fprintf(w, "Received user: %+v", user) } func connector() (*gorm.DB, error) { // Database connection string err:= godotenv.Load(); if(err!=nil) { log.Fatal("Error loading .env file") } dsn := fmt.Sprint(os.Getenv("DATABASE_DSN")) log.Print(dsn) // Open the database connection db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { log.Fatal("failed to connect database:", err) } return db, err }