Home > Backend Development > Golang > How to Build a CRUD App with Golang, Gin, and PostgreSQL

How to Build a CRUD App with Golang, Gin, and PostgreSQL

Susan Sarandon
Release: 2025-01-26 14:03:09
Original
363 people have browsed it

This tutorial shows you how to build a simple CRUD (Create, Read, Update, Delete) application using Golang, the Gin framework, and PostgreSQL. You'll learn to manage data stored in a PostgreSQL database.

How to Build a CRUD App with Golang, Gin, and PostgreSQL

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Project Structure
  4. Project Setup
  5. Database and Table Creation
  6. Implementing CRUD Handlers
  7. API Testing
  8. Conclusion

1. Introduction

This guide utilizes Gin, a lightweight Golang web framework, to create API endpoints. The application interacts with a PostgreSQL database via the pgx driver. Basic familiarity with Golang and REST APIs is assumed.

2. Prerequisites

Before starting, ensure you have:

  • Golang (version 1.20 or later)
  • PostgreSQL (any version)
  • Postman (or a similar API testing tool)
  • A code editor (e.g., VS Code)

3. Project Structure

Organize your project as follows:

<code>crud-app/
├── main.go            
├── config/
│   └── database.go    
├── controllers/
│   └── item.go        
├── models/
│   └── item.go        
├── routes/
│   └── routes.go      
├── go.mod             
└── go.sum             </code>
Copy after login

4. Project Setup

  1. Create the project directory and initialize a Go module:

    <code class="language-bash">mkdir crud-app
    cd crud-app
    go mod init github.com/yourusername/crud-app  // Replace with your GitHub username</code>
    Copy after login
  2. Install necessary packages:

    <code class="language-bash">go get github.com/gin-gonic/gin
    go get github.com/jackc/pgx/v5</code>
    Copy after login

5. Database and Table Creation

  1. Create a PostgreSQL database (e.g., crud_app).

  2. Connect to the database and create the items table:

    <code class="language-sql">CREATE DATABASE crud_app;
    \c crud_app
    CREATE TABLE items (
        id SERIAL PRIMARY KEY,
        name TEXT NOT NULL,
        description TEXT,
        price NUMERIC(10, 2)
    );</code>
    Copy after login

6. Implementing CRUD Handlers

6.1 Database Connection (config/database.go):

<code class="language-go">package config

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/jackc/pgx/v5/stdlib"
)

var DB *sql.DB

func ConnectDatabase() {
    // ... (Connection string with your credentials) ...
}</code>
Copy after login

6.2 Model Definition (models/item.go):

<code class="language-go">package models

type Item struct {
    ID          int     `json:"id"`
    Name        string  `json:"name"`
    Description string  `json:"description"`
    Price       float64 `json:"price"`
}</code>
Copy after login

6.3 CRUD Handlers (controllers/item.go): (Example: Create)

<code class="language-go">package controllers

import (
    "crud-app/config"
    "crud-app/models"
    "github.com/gin-gonic/gin"
    "net/http"
)

func CreateItem(c *gin.Context) {
    // ... (Implementation for creating a new item) ...
}</code>
Copy after login

Implement similar functions for reading, updating, and deleting items.

6.4 Route Definitions (routes/routes.go):

<code class="language-go">package routes

import (
    "crud-app/controllers"
    "github.com/gin-gonic/gin"
)

func SetupRoutes(router *gin.Engine) {
    router.POST("/items", controllers.CreateItem)
    // ... (Add routes for other CRUD operations) ...
}</code>
Copy after login

6.5 Main Application (main.go):

<code class="language-go">package main

import (
    "crud-app/config"
    "crud-app/routes"
    "github.com/gin-gonic/gin"
)

func main() {
    config.ConnectDatabase()
    r := gin.Default()
    routes.SetupRoutes(r)
    r.Run(":8080")
}</code>
Copy after login

7. API Testing

Run the application (go run main.go) and test the endpoints using Postman or a similar tool.

8. Conclusion

You've successfully created a basic CRUD application. Remember to fill in the missing CRUD handler implementations and adapt the database connection string to your environment. This foundation can be expanded upon with more advanced features.

The above is the detailed content of How to Build a CRUD App with Golang, Gin, and PostgreSQL. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template