Basic CRUD Operations Using Golang, Gin Gonic, and GORM
Tags: go, gorm, gin, restapi
Published: 2024-05-24 12:56:40

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
```

#### Setting Up the Project

1. **Initialize the project**:
   ```bash
   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
   ```

2. **Database Configuration (`configs/dbConfig.go`)**:
   ```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
   }
   ```

3. **Models (`internal/domain/models/books.go`)**:
   ```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
   }
   ```

4. **Repositories (`internal/domain/repositories/bookRepo.go`)**:
   ```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
   ```

5. **Services (`internal/domain/services/bookService.go`)**:
   ```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
   ```

6. **Handlers (`internal/delivery/handlers/bookHandler.go`)**:
   ```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
   ```

7. **Router (`internal/delivery/router/bookRouter.go`)**:
   ```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
   }
   ```

8. **Main (`cmd/main.go`)**:
   ```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
   }
   ```

### 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](https://blog.awahids.my.id/blog/golang/example-basic-crud-using-golang-gin-gonic-gorm)