How to Build a CRUD REST API in Go (Golang) with PostgreSQL – Step-by-Step Guide

CRUD API in Go with PostgreSQL

🧑‍💻 Building a CRUD API in Go with PostgreSQL – A Practical Guide

Go PostgreSQL API Banner

If you're diving into backend development with Go (Golang) and looking for a simple and effective way to manage data, this post is for you. Today, we’ll walk through building a basic CRUD (Create, Read, Update, Delete) REST API in Go, backed by a PostgreSQL database.

Whether you're building a full-stack app or microservice, this guide will give you the solid foundation you need.

🚀 Why Go and PostgreSQL?

Go is known for its performance, simplicity, and strong concurrency support, while PostgreSQL is a powerful, open-source relational database that’s trusted in production environments everywhere. Together, they’re a robust combination for scalable backend services.

🪰 What We'll Use

  • Go (v1.20+ recommended)
  • PostgreSQL (v13+)
  • Gorilla Mux (for routing)
  • Standard library (database/sql with lib/pq driver)

📦 Project Structure

go-postgres-crud/
├── main.go
├── db.go
├── handlers.go
├── models.go
└── go.mod

🔧 Step 1: Setup Your Go Project

go mod init go-postgres-crud
go get github.com/lib/pq
go get github.com/gorilla/mux

📃 Step 2: Create the PostgreSQL Table

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name TEXT NOT NULL,
  email TEXT UNIQUE NOT NULL
);

🔌 Step 3: Database Connection (db.go)

package main

import (
    "database/sql"
    "log"
    _ "github.com/lib/pq"
)

var db *sql.DB

func InitDB() {
    var err error
    connStr := "user=postgres password=yourpass dbname=cruddb sslmode=disable"
    db, err = sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }

    if err = db.Ping(); err != nil {
        log.Fatal(err)
    }

    log.Println("Connected to database")
}

👤 Step 4: Create a Model (models.go)

package main

type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}

🧩 Step 5: Build the Handlers (handlers.go)

🚀 Step 6: Start the Server (main.go)

package main

import (
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

func main() {
    InitDB()
    r := mux.NewRouter()
    r.HandleFunc("/users", CreateUser).Methods("POST")
    r.HandleFunc("/users", GetUsers).Methods("GET")
    r.HandleFunc("/users/{id}", UpdateUser).Methods("PUT")
    r.HandleFunc("/users/{id}", DeleteUser).Methods("DELETE")
    log.Println("Server running on port 8080")
    log.Fatal(http.ListenAndServe(":8080", r))
}

🥺 Testing the API

  • Create:
    curl -X POST -H "Content-Type: application/json" -d '{"name":"Alice", "email":"alice@example.com"}' http://localhost:8080/users
  • Read:
    curl http://localhost:8080/users
  • Update:
    curl -X PUT -H "Content-Type: application/json" -d '{"name":"Alicia", "email":"alicia@example.com"}' http://localhost:8080/users/1
  • Delete:
    curl -X DELETE http://localhost:8080/users/1

✅ Conclusion

That’s it! You’ve now built a basic Go REST API connected to a PostgreSQL database with full CRUD functionality. This setup is ideal for small apps, microservices, or as a backend for a frontend framework like React or Vue.

Want to take it further? Add JWT authentication, Dockerize the app, or switch to an ORM like GORM or sqlc.

you might also like this article

Post a Comment

0 Comments