
Getting Started - GORM in Go Part 1
If you're coming from a JavaScript or TypeScript environment, you might already be familiar with ORMs like Mongoose, Sequelize, or Prisma. In the Go ecosystem, there's GORM — one of the most popular Object Relational Mappers available.
In this article, we’ll explore how to get started with GORM in Go, from setting up the project to performing basic database operations. Whether you're new to Go or just looking for a solid way to manage your database layer, this guide will help you get up and running with GORM quickly.
Prerequisites
Before getting started, make sure you have:
- PostgreSQL installed on your machine
- Go programming language installed (version 1.20 or above is recommended)
Setting Up the Project
Let's start by creating a new Go project and initializing the module:
mkdir gorm-in-go
cd gorm-in-go
go mod init gorm-in-go
We’ll also follow the Clean Architecture approach inspired by Uncle Bob. This helps us separate concerns and keep our codebase scalable and maintainable. Here’s the proposed folder structure:
│ .env
│ go.mod
│ go.sum
│
├───.vscode
│ settings.json
│
├───cmd
│ main.go # Entry point of the application
│
├───deployment
│ Dockerfile # Container configuration
│
├───internal
│ └───api
│ └───http
│ │ server.go # Fiber Framework Setup
│ │
│ └───user
│ user_handler.go # HTTP request handling logic
│ user_routes.go # User-related routes
│
└───pkg
├───app
│ └───user
│ ├───repository
│ │ user_repository.go # Data access layer
│ │
│ └───service
│ user_service.go # Business logic layer
│
├───database
│ database.go # DB connection setup
│ migration.go # Schema migrations
│
└───models
user_model.go # GORM models
Installing Required Packages
With the folder structure in place, let’s install the packages we’ll be using in this project:
go get github.com/gofiber/fiber/v2 # Fiber web framework
go get github.com/joho/godotenv # Load environment variables from .env
go get -u gorm.io/gorm # GORM ORM package
go get gorm.io/driver/postgres # PostgreSQL driver for GORM
1. Setting Up the Database Connection
Let’s begin by initializing our database connection using GORM and PostgreSQL. We’ll also make use of environment variables via godotenv to keep our config clean and secure.
pkg/database/database.go
package database
import (
"fmt"
"log"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var db *gorm.DB
// InitDB initializes the database connection using the provided credentials
func InitDB(host, user, password, dbname, port string) (*gorm.DB, error) {
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Jakarta",
host, user, password, dbname, port)
var err error
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("failed to connect to database %v", err)
}
log.Println("Successfully connect to database")
return db, nil
}
// GetDB returns the database connection
func GetDB() *gorm.DB {
return db
}
2. Setting Up the Fiber Web Framework
Fiber is a Go web framework built on top of Fasthttp, the fastest HTTP engine for Go. It's designed to ease things up for fast development with zero memory allocation and performance in mind.
Let’s set up a basic web server using Fiber.
internal/api/http/server.go
package server
import "github.com/gofiber/fiber/v2"
func StartServer() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello World!")
})
app.Listen(":8080")
}
3. Putting It All Together in main.go
We’ve done the setup—installed packages, initialized the database, and created our server. Now it’s time to tie everything together in the main.go entry point.
cmd/main.go
package main
import (
server "gorm-in-go/internal/api/http"
"gorm-in-go/pkg/database"
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
godotenv.Load() # Load env variables
// Initialize database
_, err := database.InitDB(
os.Getenv("DB_HOST"), // host
os.Getenv("DB_USER"), // user
os.Getenv("DB_PASSWORD"), // password
os.Getenv("DB_NAME"), // database name
os.Getenv("DB_PORT"), // port
)
if err != nil {
log.Fatal(err)
}
server.StartServer()
}
4. Running The App
Once everything is set up, you can run your Go application with:
go run ./cmd/main.go
If everything goes smoothly, your terminal should display a message indicating that the server is running and connected to the database—something like this:
Conclusion
In this article, we walked through the initial setup of a Go project using GORM with Clean Code Architecture principles. We:
- Structured the project in a scalable way
- Installed essential dependencies including Fiber, Godotenv, and GORM
- Configured a PostgreSQL database connection
- Bootstrapped a basic HTTP server using Fiber
This sets a strong foundation for building scalable Go applications with clean separation of concerns.
What's Next?
In the next part, we’ll move forward by creating our first User
model, setting up migrations, and building basic CRUD operations using GORM.
Stay tuned and happy coding!
You can view the complete project on GitHub