Minimal app with Go,Gorm and Psql
By admin | 9 months ago
To create a basic CRUD application in Go using Gorm and PostgreSQL, you need to have Go installed on your machine, PostgreSQL setup, and the Gorm package included in your project. Here's a step-by-step guide to set up a basic CRUD application:
Step 1: Install Go
Ensure Go is installed on your system. You can download it from the Go website.
Step 2: Set Up PostgreSQL
Install PostgreSQL if it's not already installed. Create a database and a user with the necessary permissions. You can follow instructions specific to your operating system.
Step 3: Initialize Your Go Project
Create a new directory for your project and initialize a new Go module:
mkdir go-gorm-crud cd go-gorm-crud go mod init go-gorm-crud
Step 4: Install Gorm and PostgreSQL Driver
Run the following command to get Gorm and the PostgreSQL driver:
go get -u gorm.io/gorm go get -u gorm.io/driver/postgres
Step 5: Create Your Go Application
Create a file, for example, main.go
, and set up your application. Here's a basic outline of what the application will look like:
package main import ( "fmt" "gorm.io/driver/postgres" "gorm.io/gorm" ) // Define a model type Product struct { gorm.Model Code string Price uint } func main() { // Connect to the database dsn := "host=localhost user=youruser password=yourpassword dbname=yourdb port=5432 sslmode=disable TimeZone=Asia/Shanghai" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic("failed to connect to database") } // Automatically migrate your schema db.AutoMigrate(&Product{}) // Create db.Create(&Product{Code: "D42", Price: 100}) // Read var product Product db.First(&product, 1) // find product with integer primary key db.First(&product, "code = ?", "D42") // find product with code D42 // Update - update product's price to 200 db.Model(&product).Update("Price", 200) // Delete - delete product db.Delete(&product, 1) }
Replace youruser
, yourpassword
, yourdb
, and other database connection details with your actual PostgreSQL connection information.
This application defines a `Product` model, connects to a PostgreSQL database, automatically migrates the database schema, and performs basic CRUD operations.
Step 6: Run Your Application
Run your application using the command:
go run main.go
This will execute the CRUD operations defined in your `main` function.
This basic setup gives you a starting point for a CRUD application using Go, Gorm, and PostgreSQL. You can expand this by adding more routes, handling HTTP requests, and structuring your application with different packages for models, controllers, and routes.
feel free to checkout latest golang jobs in kerala