DEV Community

wahid
wahid

Posted on

Basic CRUD Operations Using Golang, Gin Gonic, and GORM

Building web applications in Golang is both fun and efficient. Using powerful frameworks like Gin Gonic for the web layer and GORM for ORM (Object-Relational Mapping) makes it easier to create robust and maintainable applications. In this tutorial, we'll demonstrate how to implement basic CRUD operations in a book management system.

Project Structure

We will organize our project using the following structure to maintain clean and manageable code:

belajar-go/
│
├── cmd/
│     └── main.go
├── configs/
│     └── dbConfig.go
├── internal/
│     ├── delivery/
│     │     ├── handlers/
│     │     │     └── bookHandler/
│     │     │          └── bookHandler.go
│     │     ├── data/
│     │     │     ├── request/
│     │     │     │     └── bookReq/
│     │     │     │          └── bookRequest.go
│     │     │     └── response/
│     │     │          ├── bookRes/
│     │     │          │     └── bookResponse.go
│     │     │          └── response.go
│     │     └── router/
│     │           ├── bookRouter/
│     │           │          └── bookRouter.go
│     │           └── router.go
│     ├── domain/
│     │     ├── models/
│     │     │     └── books.go
│     │     ├── repositories/
│     │     │     ├── bookRepo/
│     │     │     │      └── bookRepo.go
│     │     └── services/
│     │           ├── bookService/
│     │           │      └── bookService.go
│     └── infrastructure/
│           └── database/
│                  ├── database.go
│                  └── migrations.go
├── pkg/
│     ├── utils/
│     │     └── base.go
│     └── helpers/
│           └── errorPanic.go
├── .env.example
├── .gitignore
├── go.mod
└── go.sum
Enter fullscreen mode Exit fullscreen mode

Setting Up the Project

  1. Initialize the project:
   go mod init github.com/your-username/belajar-go
   go get -u github.com/gin-gonic/gin
   go get -u gorm.io/gorm
   go get -u gorm.io/driver/postgres
Enter fullscreen mode Exit fullscreen mode
  1. Database Configuration (configs/dbConfig.go):
   package configs

   import (
       "gorm.io/driver/postgres"
       "gorm.io/gorm"
   )

   func ConnectDB() (*gorm.DB, error) {
       dsn := "host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai"
       db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
       if err != nil {
           return nil, err
       }
       return db, nil
   }
Enter fullscreen mode Exit fullscreen mode
  1. Models (internal/domain/models/books.go):
   package models

   import (
       "time"
   )

   type Book struct {
       ID        uint      `gorm:"primaryKey"`
       UUID      string    `gorm:"type:uuid;default:uuid_generate_v4()"`
       Title     string    `gorm:"size:255"`
       Author    string    `gorm:"size:255"`
       Year      int
       CreatedAt time.Time
       UpdatedAt time.Time
   }
Enter fullscreen mode Exit fullscreen mode
  1. Repositories (internal/domain/repositories/bookRepo.go):
   package repositories

   import (
       "github.com/your-username/belajar-go/internal/domain/models"
       "gorm.io/gorm"
   )

   type BookRepository struct {
       Db *gorm.DB
   }

   func NewBookRepository(Db *gorm.DB) *BookRepository {
       return &BookRepository{Db: Db}
   }

   // Implement CRUD operations
Enter fullscreen mode Exit fullscreen mode
  1. Services (internal/domain/services/bookService.go):
   package services

   import (
       "github.com/your-username/belajar-go/internal/domain/models"
       "github.com/your-username/belajar-go/internal/domain/repositories"
   )

   type BookService struct {
       repo *repositories.BookRepository
   }

   func NewBookService(repo *repositories.BookRepository) *BookService {
       return &BookService{repo: repo}
   }

   // Implement service methods
Enter fullscreen mode Exit fullscreen mode
  1. Handlers (internal/delivery/handlers/bookHandler.go):
   package handlers

   import (
       "net/http"

       "github.com/gin-gonic/gin"
       "github.com/your-username/belajar-go/internal/domain/models"
       "github.com/your-username/belajar-go/internal/domain/services"
   )

   type BookHandler struct {
       bookService *services.BookService
   }

   func NewBookHandler(bookService *services.BookService) *BookHandler {
       return &BookHandler{bookService: bookService}
   }

   // Implement handler methods
Enter fullscreen mode Exit fullscreen mode
  1. Router (internal/delivery/router/bookRouter.go):
   package router

   import (
       "github.com/gin-gonic/gin"
       "github.com/your-username/belajar-go/internal/delivery/handlers"
       "github.com/your-username/belajar-go/internal/domain/repositories"
       "github.com/your-username/belajar-go/internal/domain/services"
       "gorm.io/gorm"
   )

   func BookRouter(group *gin.RouterGroup, db *gorm.DB) {
       // Setup routing
   }
Enter fullscreen mode Exit fullscreen mode
  1. Main (cmd/main.go):
   package main

   import (
       "github.com/gin-gonic/gin"
       "github.com/your-username/belajar-go/configs"
       "github.com/your-username/belajar-go/internal/delivery/router"
   )

   func main() {
       // Setup server
   }
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following this guide, you've learned how to create a basic CRUD application using Golang, Gin Gonic, and GORM. This structure helps in maintaining and scaling your application effectively. Happy coding!

For full code klick here

Top comments (2)

Collapse
 
bayaderpack profile image
bayaderpack

instead of declaring
ID uint gorm:"primaryKey"
CreatedAt time.Time
UpdatedAt time.Time

You can use gorm.Model

Collapse
 
awahids profile image
wahid

Thanks