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.
Table of Contents
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:
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>
4. Project Setup
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>
Install necessary packages:
<code class="language-bash">go get github.com/gin-gonic/gin go get github.com/jackc/pgx/v5</code>
5. Database and Table Creation
Create a PostgreSQL database (e.g., crud_app
).
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>
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>
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>
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>
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>
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>
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!