Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Updates to LogRocket's Gin Gonic tutorial article
package controllers
import (
"Go-Tutorials/models"
"github.com/gin-gonic/gin"
"net/http"
)
type CreateBookInput struct {
Title string `json:"title" binding:"required"`
Author string `json:"author" binding:"required"`
}
type UpdateBookInput struct {
Title string `json:"title"`
Author string `json:"author"`
}
func FindBooks(c *gin.Context) {
var books []models.Book
models.DB.Find(&books)
c.JSON(http.StatusOK, gin.H{"data": books})
}
func CreateBook(c *gin.Context) {
// Validate input
var input CreateBookInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Create book
book := models.Book{Title: input.Title, Author: input.Author}
models.DB.Create(&book)
c.JSON(http.StatusOK, gin.H{"data": book})
}
func FindBook(c *gin.Context) { // Get model if exist
var book models.Book
if err := models.DB.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
c.JSON(http.StatusOK, gin.H{"data": book})
}
func UpdateBook(c *gin.Context) {
// Get model if exist
var book models.Book
if err := models.DB.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
// Validate input
var input UpdateBookInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
models.DB.Model(&book).Updates(input)
c.JSON(http.StatusOK, gin.H{"data": book})
}
func DeleteBook(c *gin.Context) {
// Get model if exist
var book models.Book
if err := models.DB.Where("id = ?", c.Param("id")).First(&book).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"})
return
}
models.DB.Delete(&book)
c.JSON(http.StatusOK, gin.H{"data": true})
}
package main
import (
"Go-Tutorials/controllers"
"Go-Tutorials/models"
"github.com/gin-gonic/gin"
)
func main() {
// ...
r := gin.Default()
models.ConnectDatabase()
r.GET("/books", controllers.FindBooks)
r.POST("/books", controllers.CreateBook)
r.GET("/books/:id", controllers.FindBook)
r.PATCH("/books/:id", controllers.UpdateBook)
r.DELETE("/books/:id", controllers.DeleteBook) // new
err := r.Run()
if err != nil {
return
}
}
package models
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type Book struct {
ID uint `json:"id" gorm:"primary_key"`
Title string `json:"title"`
Author string `json:"author"`
}
var DB *gorm.DB
func ConnectDatabase() {
database, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
panic("Failed to connect to database!")
}
err = database.AutoMigrate(&Book{})
if err != nil {
return
}
DB = database
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment