Gin and GORM simple sample

Example is based on
1. Connect to a Postgres DB using GORM

2. Create a User table in the DB

3. Use Get and Post method using Gin

CODE:

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type User struct {
	gorm.Model
	Name  string
	Email string
}

func main() {
	// Create a new Gin router
	router := gin.Default()

	// Connect to the PostgreSQL database
	dsn := "host=localhost user=postgres password=postgres dbname=mydatabase port=5432 sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}
	
	// Migrate the database schema
	db.AutoMigrate(&User{})

	// Define a route to retrieve a list of users
	router.GET("/users", func(c *gin.Context) {
		var users []User
		result := db.Find(&users)
		if result.Error != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		c.JSON(http.StatusOK, users)
	})

	// Define a route to create a new user
	router.POST("/users", func(c *gin.Context) {
		var user User
		if err := c.BindJSON(&user); err != nil {
			c.AbortWithStatus(http.StatusBadRequest)
			return
		}
		result := db.Create(&user)
		if result.Error != nil {
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		c.JSON(http.StatusCreated, user)
	})

	// Start the server
	router.Run(":8080")
}

In this example, we define a User struct that represents a user in our database. We then create a new Gin router and connect to a PostgreSQL database using GORM’s PostgreSQL driver. We use GORM’s AutoMigrate function to automatically create the users table in the database.

We define two routes: one to retrieve a list of all users in the database, and one to create a new user. In the GET route, we use GORM’s Find function to retrieve all users from the database. In the POST route, we use Gin’s BindJSON function to bind the request body to a User struct, and then use GORM’s Create function to insert the new user into the database.

Note that this is just a simple example, and in a real-world application you would likely want to add more error handling and validation to ensure that your application is robust and secure.

GORM Were clause

In GORM, you can use the Where method to add a WHERE clause to your query. The Where method takes either a string representing a raw SQL WHERE clause, or a map representing a series of key-value pairs that will be used to build the WHERE clause.

Here’s an example of using the Where method to filter a query by a specific value:

// Find all users with the name "John"
var users []User
db.Where("name = ?", "John").Find(&users)

In this example, we’re using a string to specify the WHERE clause. The ? character is a placeholder for the value we want to filter by, which in this case is “John”.

var users []User
db.Where(map[string]interface{}{"name": "John", "email": "john@example.com"}).Find(&users)

In this example, we’re using a map to specify the WHERE clause. The keys in the map represent the columns we want to filter by, and the values represent the values we want to filter for.

var users []User
db.Where("name = ?", "John").Or("email = ?", "john@example.com").Find(&users)

In this example, we’re using the Or method to combine two Where clauses. This will retrieve all users who have the name “John” OR the email “john@example.com“.

Here’s an example of using Raw to execute a simple SQL query:

var user User
db.Raw("SELECT * FROM users WHERE id = ?", 1).Scan(&user)

In this example, we’re executing a raw SQL query to select a single user from the users table based on their ID. We’re using the Scan method to map the results of the query to a User struct.

You can also use Raw to execute more complex SQL queries that join multiple tables or perform complex filtering:

type UserWithPosts struct {
    ID    uint
    Name  string
    Email string
    Posts []Post
}
var userWithPosts UserWithPosts
db.Raw("SELECT users.id, users.name, users.email, posts.id AS post_id, posts.title, 
posts.content FROM users JOIN posts ON users.id = 
posts.user_id WHERE users.id = ?", 1).Scan(&userWithPosts)

In this example, we’re executing a raw SQL query to join the users and posts tables and select all posts belonging to a specific user. We’re using a custom struct UserWithPosts to map the results of the query to a struct with nested Post objects.

Leave a Reply

Your email address will not be published. Required fields are marked *

+ 80 = 84

Related Post