惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
D
Docker
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
V
Visual Studio Blog
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
Recent Announcements
Recent Announcements
GbyAI
GbyAI
T
Tailwind CSS Blog
S
SegmentFault 最新的问题
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
Engineering at Meta
Engineering at Meta
L
LangChain Blog
A
About on SuperTechFans
M
MIT News - Artificial intelligence
B
Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
🚀 Building a CRUD API in Go with PostgreSQL (Step-by-Step)
Ahmed Raza I · 2026-04-27 · via DEV Community
Cover image for 🚀 Building a CRUD API in Go with PostgreSQL (Step-by-Step)

Ahmed Raza Idrisi

In the previous post, we built a simple CRUD API in Go using in-memory storage.

Now let’s make it real-world ready by connecting it to a database:

👉 PostgreSQL


⚙️ Step 1: Install PostgreSQL Driver

We’ll use the official driver:

go get github.com/lib/pq

Enter fullscreen mode Exit fullscreen mode


🧱 Step 2: Setup Database Connection

package main

import (
    "database/sql"
    "log"

    _ "github.com/lib/pq"
)

var db *sql.DB

func initDB() {
    connStr := "user=postgres password=postgres dbname=testdb sslmode=disable"

    var err error
    db, err = sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
    }

    err = db.Ping()
    if err != nil {
        log.Fatal("DB not reachable:", err)
    }

    log.Println("Connected to PostgreSQL ✅")
}

Enter fullscreen mode Exit fullscreen mode


🗄️ Step 3: Create Table

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

Enter fullscreen mode Exit fullscreen mode


🧩 Step 4: Model

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

Enter fullscreen mode Exit fullscreen mode


➕ Create User (INSERT)

func createUser(w http.ResponseWriter, r *http.Request) {
    var user User
    json.NewDecoder(r.Body).Decode(&user)

    err := db.QueryRow(
        "INSERT INTO users(name) VALUES($1) RETURNING id",
        user.Name,
    ).Scan(&user.ID)

    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    json.NewEncoder(w).Encode(user)
}

Enter fullscreen mode Exit fullscreen mode


📥 Get Users (SELECT)

func getUsers(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query("SELECT id, name FROM users")
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }
    defer rows.Close()

    var users []User

    for rows.Next() {
        var user User
        rows.Scan(&user.ID, &user.Name)
        users = append(users, user)
    }

    json.NewEncoder(w).Encode(users)
}

Enter fullscreen mode Exit fullscreen mode


✏️ Update User

func updateUser(w http.ResponseWriter, r *http.Request) {
    idParam := r.URL.Query().Get("id")

    var user User
    json.NewDecoder(r.Body).Decode(&user)

    _, err := db.Exec(
        "UPDATE users SET name=$1 WHERE id=$2",
        user.Name, idParam,
    )

    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    json.NewEncoder(w).Encode("Updated")
}

Enter fullscreen mode Exit fullscreen mode


❌ Delete User

func deleteUser(w http.ResponseWriter, r *http.Request) {
    idParam := r.URL.Query().Get("id")

    _, err := db.Exec("DELETE FROM users WHERE id=$1", idParam)
    if err != nil {
        http.Error(w, err.Error(), 500)
        return
    }

    json.NewEncoder(w).Encode("Deleted")
}

Enter fullscreen mode Exit fullscreen mode


🌐 Step 5: Main Function

func main() {
    initDB()

    http.HandleFunc("/users", getUsers)
    http.HandleFunc("/create", createUser)
    http.HandleFunc("/update", updateUser)
    http.HandleFunc("/delete", deleteUser)

    log.Println("Server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Enter fullscreen mode Exit fullscreen mode


🧪 Test API

Same as before, but now data is stored in PostgreSQL 🎉


⚠️ Improvements You Should Do Next

This is still beginner-level. To make it production-ready:

  • Use environment variables for DB config
  • Add validation
  • Use a router (Chi / Gorilla Mux)
  • Structure code (controllers, services, repo)
  • Add connection pooling tuning

🔥 What You Learned

  • Connecting Go to PostgreSQL
  • Executing SQL queries (INSERT, SELECT, UPDATE, DELETE)
  • Handling real database-backed APIs

🚀 Coming Next

👉 Proper API structure in Go (like Laravel mindset)
👉 Using Docker with Go + PostgreSQL
👉 Adding authentication (JWT)


💬 Final Thought

Now you're no longer just learning Go…

👉 You're building backend systems.