首页 后端开发 Golang Golang RESTful API 与 Gin、Gorm、PostgreSQL

Golang RESTful API 与 Gin、Gorm、PostgreSQL

Oct 29, 2024 pm 09:20 PM

Golang RESTful API with Gin, Gorm, PostgreSQL

Golang RESTful API 服务的综合示例,该服务使用 gin 进行路由、gorm 进行 ORM 以及 PostgreSQL 作为数据库。此示例包括以下 PostgreSQL 功能:数据库和表创建、数据插入和查询、索引、函数和存储过程、触发器、视图、CTE、事务、约束和 JSON 处理。

1. 项目设置

假设你已经设置了 PostgreSQL、Golang 和 go mod,初始化项目:

mkdir library-api
cd library-api
go mod init library-api
登录后复制
登录后复制
登录后复制

项目结构

/library-api
|-- db.sql
|-- main.go
|-- go.mod
登录后复制
登录后复制

2.安装依赖项

安装必要的软件包:

go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/postgres
登录后复制
登录后复制

3.PostgreSQL 架构

这是一个用于创建数据库模式的 SQL 脚本:

-- Create the library database.
CREATE DATABASE library;

-- Connect to the library database.
\c library;

-- Create tables.
CREATE TABLE authors (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL UNIQUE,
    bio TEXT
);

CREATE TABLE books (
    id SERIAL PRIMARY KEY,
    title VARCHAR(200) NOT NULL,
    -- This creates a foreign key constraint:
    -- It establishes a relationship between author_id in the books table and the id column in the authors table, ensuring that each author_id corresponds to an existing id in the authors table.
    -- ON DELETE CASCADE: This means that if an author is deleted from the authors table, all related records in the books table (i.e., books written by that author) will automatically be deleted as well.
    author_id INTEGER REFERENCES authors(id) ON DELETE CASCADE,
    published_date DATE NOT NULL,
    description TEXT,
    details JSONB
);

CREATE TABLE users (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) UNIQUE NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- CREATE TABLE borrow_logs (
--     id SERIAL PRIMARY KEY,
--     user_id INTEGER REFERENCES users(id),
--     book_id INTEGER REFERENCES books(id),
--     borrowed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
--     returned_at TIMESTAMP
-- );

-- Create a partitioned table for borrow logs based on year.
-- The borrow_logs table is partitioned by year using PARTITION BY RANGE (borrowed_at).
CREATE TABLE borrow_logs (
    id SERIAL PRIMARY KEY,
    user_id INTEGER REFERENCES users(id),
    book_id INTEGER REFERENCES books(id),
    borrowed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    returned_at TIMESTAMP
) PARTITION BY RANGE (borrowed_at);

-- Create partitions for each year.
-- Automatic Routing: PostgreSQL automatically directs INSERT operations to the appropriate partition (borrow_logs_2023 or borrow_logs_2024) based on the borrowed_at date.
CREATE TABLE borrow_logs_2023 PARTITION OF borrow_logs
    FOR VALUES FROM ('2023-01-01') TO ('2024-01-01');

CREATE TABLE borrow_logs_2024 PARTITION OF borrow_logs
    FOR VALUES FROM ('2024-01-01') TO ('2025-01-01');
-- Benefit: This helps in improving query performance and managing large datasets by ensuring that data for each year is stored separately.



-- Indexes for faster searching.
CREATE INDEX idx_books_published_date ON books (published_date);
CREATE INDEX idx_books_details ON books USING GIN (details);
-- GIN Index (Generalized Inverted Index).  It is particularly useful for indexing columns with complex data types like arrays, JSONB, or text search fields


-- Add a full-text index to the title and description of books
CREATE INDEX book_text_idx ON books USING GIN (to_tsvector('english', title || ' ' || description));
-- to_tsvector('english', ...) converts the concatenated title and description fields into a Text Search Vector (tsv) suitable for full-text searching.
-- The || operator concatenates the title and description fields, so both fields are indexed together for searching.
-- 'english' specifies the language dictionary, which helps with stemming and stop-word filtering.


-- Create a simple view for books with author information.
CREATE VIEW book_author_view AS
SELECT books.id AS book_id, books.title, authors.name AS author_name
FROM books
JOIN authors ON books.author_id = authors.id;

-- Create a view to get user borrow history
CREATE VIEW user_borrow_history AS
SELECT
    u.id AS user_id,
    u.name AS user_name,
    b.title AS book_title,
    bl.borrowed_at,
    bl.returned_at
FROM
    users u
    JOIN borrow_logs bl ON u.id = bl.user_id
    JOIN books b ON bl.book_id = b.id;

-- Use a CTE to get all active borrow logs (not yet returned)
WITH active_borrows AS (
    SELECT * FROM borrow_logs WHERE returned_at IS NULL
)
SELECT * FROM active_borrows;

-- Function to calculate the number of books borrowed by a user.
-- Creates a function that takes an INT parameter user_id and returns an INT value. If the function already exists, it will replace it.
CREATE OR REPLACE FUNCTION get_borrow_count(user_id INT) RETURNS INT AS $$
    --  is a placeholder for the first input. When the function is executed, PostgreSQL replaces  with the actual user_id value that is passed in by the caller.
    SELECT COUNT(*) FROM borrow_logs WHERE user_id = ;
$$ LANGUAGE SQL;
-- AS $$ ... $$: This defines the body of the function between the dollar signs ($$).
-- LANGUAGE SQL: Specifies that the function is written in SQL.


-- Trigger to log activities.
CREATE TABLE activity_logs (
    id SERIAL PRIMARY KEY,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE OR REPLACE FUNCTION log_activity() RETURNS TRIGGER AS $$
BEGIN
    INSERT INTO activity_logs (description)
    -- NEW refers to the new row being inserted or modified by the triggering event.
    VALUES ('A borrow_log entry has been added with ID ' || NEW.id);
    -- The function returns NEW, which means that the new data will be used as it is after the trigger action.
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- It uses plpgsql, which is a procedural language in PostgreSQL

CREATE TRIGGER log_borrow_activity
AFTER INSERT ON borrow_logs
FOR EACH ROW EXECUTE FUNCTION log_activity();

-- Add a JSONB column to store metadata
ALTER TABLE books ADD COLUMN metadata JSONB;
-- Example metadata: {"tags": ["fiction", "bestseller"], "page_count": 320}
登录后复制

4.Go语言代码

这是使用 Gin 和 GORM 的 RESTful API 的完整示例:

package main

import (
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

type Author struct {
    ID   uint   `gorm:"primaryKey"`
    Name string `gorm:"not null;unique"`
    Bio  string
}

type Book struct {
    ID            uint                   `gorm:"primaryKey"`
    Title         string                 `gorm:"not null"`
    AuthorID      uint                   `gorm:"not null"`
    PublishedDate time.Time              `gorm:"not null"`
    Details       map[string]interface{} `gorm:"type:jsonb"`
}

type User struct {
    ID        uint   `gorm:"primaryKey"`
    Name      string `gorm:"not null"`
    Email     string `gorm:"not null;unique"`
    CreatedAt time.Time
}

type BorrowLog struct {
    ID         uint      `gorm:"primaryKey"`
    UserID     uint      `gorm:"not null"`
    BookID     uint      `gorm:"not null"`
    BorrowedAt time.Time `gorm:"default:CURRENT_TIMESTAMP"`
    ReturnedAt *time.Time
}

var db *gorm.DB

func initDB() {
    dsn := "host=localhost user=postgres password=yourpassword dbname=library port=5432 sslmode=disable"
    var err error
    db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
    if err != nil {
        panic("failed to connect to database")
    }

    // Auto-migrate models.
    db.AutoMigrate(&Author{}, &Book{}, &User{}, &BorrowLog{})
}

func main() {
    initDB()
    r := gin.Default()

    r.POST("/authors", createAuthor)
    r.POST("/books", createBook)
    r.POST("/users", createUser)
    r.POST("/borrow", borrowBook)
    r.GET("/borrow/:id", getBorrowCount)
    r.GET("/books", listBooks)

    r.Run(":8080")
}

func createAuthor(c *gin.Context) {
    var author Author
    if err := c.ShouldBindJSON(&author); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    if err := db.Create(&author).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, author)
}

func createBook(c *gin.Context) {
    var book Book
    if err := c.ShouldBindJSON(&book); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    if err := db.Create(&book).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, book)
}

func createUser(c *gin.Context) {
    var user User
    if err := c.ShouldBindJSON(&user); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }
    if err := db.Create(&user).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, user)
}

// The Golang code does not need changes specifically to use the partitioned tables; the partitioning is handled by PostgreSQL
// you simply insert into the borrow_logs table, and PostgreSQL will automatically route the data to the correct partition.
func borrowBook(c *gin.Context) {
    var log BorrowLog
    if err := c.ShouldBindJSON(&log); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    tx := db.Begin()
    if err := tx.Create(&log).Error; err != nil {
        tx.Rollback()
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    tx.Commit()
    c.JSON(http.StatusOK, log)
}

func getBorrowCount(c *gin.Context) {
    userID := c.Param("id")
    var count int
    if err := db.Raw("SELECT get_borrow_count(?)", userID).Scan(&count).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, gin.H{"borrow_count": count})
}

// When querying a partitioned table in PostgreSQL using Golang, no changes are needed in the query logic or code.
// You interact with the parent table (borrow_logs in this case) as you would with any normal table, and PostgreSQL automatically manages retrieving the data from the appropriate partitions.
// Performance: PostgreSQL optimizes the query by scanning only the relevant partitions, which can significantly speed up queries when dealing with large datasets.
// Here’s how you might query the borrow_logs table using GORM, even though it’s partitioned:
func getBorrowLogs(c *gin.Context) {
    var logs []BorrowLog
    if err := db.Where("user_id = ?", c.Param("user_id")).Find(&logs).Error; err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    c.JSON(http.StatusOK, logs)
}

func listBooks(c *gin.Context) {
    var books []Book
    db.Preload("Author").Find(&books)
    c.JSON(http.StatusOK, books)
}
登录后复制

Golang代码说明:

  • 数据库初始化:连接PostgreSQL数据库并初始化GORM。
  • 路由:定义创建作者、书籍、用户、借阅书籍以及获取借阅计数的路由。
  • 事务处理:借书时使用事务来确保一致性。
  • Preload:使用 GORM 的 Preload 来连接相关表(作者与书籍)。
  • 存储过程调用:使用 db.Raw 调用自定义 PostgreSQL 函数来计算借用计数。

5. 运行API

  • 运行 PostgreSQL SQL 脚本来创建表、索引、视图、函数和触发器。
  • 使用
    启动Golang服务器

     go run main.go
    
    登录后复制

现在,您拥有了一个全面的Golang RESTful API,它涵盖了各种 PostgreSQL 功能,使其成为学习或面试的强大示例。

6.添加更多功能。

让我们通过合并 视图CTE(通用表表达式)全文索引来增强 Golang RESTful API 示例以及其他 PostgreSQL 功能JSON 处理。这些功能中的每一个都将通过相关的 PostgreSQL 表定义和与它们交互的 Golang 代码进行演示。

这部分的数据架构已经在上一节中准备好了,所以我们只需要添加更多的 golang 代码即可。

mkdir library-api
cd library-api
go mod init library-api
登录后复制
登录后复制
登录后复制

特点总结:

  • 视图:使用 user_borrow_history 视图简化对数据的访问,使复杂的联接更易于查询。
  • CTE:使用WITH子句进行有组织的查询,例如获取活动借用日志。
  • 全文索引:通过 to_tsvector 上的 GIN 索引增强书籍的搜索能力。
  • JSON 处理

    • 使用 JSONB 类型存储和更新丰富的元数据。
    • getBookTags 从元数据 JSONB 列中检索特定的 JSON 字段(标签)。
    • updateBookPageCount 更新或添加元数据 JSONB 列中的 page_count 字段。

    通过将 db.Raw 和 db.Exec 用于 GORM 的原始 SQL,您可以利用 PostgreSQL 的强大功能,同时为应用程序的其他部分保留 GORM 的 ORM 功能。这使得该解决方案既灵活又功能丰富。

7.其他高级功能

在这个扩展示例中,我将展示如何使用 Golang 和 PostgreSQL 集成以下功能:

  1. VACUUM:用于回收死元组占用的存储并防止表膨胀。
  2. MVCC:通过维护不同版本的行来允许并发事务的概念。
  3. 窗口函数:用于在与当前行相关的一组表行上执行计算。

1.在Golang中使用VACUUM

VACUUM 通常用作维护任务,而不是直接来自应用程序代码。但是,您可以使用 GORM 的 Exec 来运行它以进行内务管理:

/library-api
|-- db.sql
|-- main.go
|-- go.mod
登录后复制
登录后复制
  • VACUUM ANALYZE books:回收存储并更新查询规划器为 books 表使用的统计信息。
  • 运行 VACUUM 通常是在非高峰时段或作为维护脚本的一部分而不是针对每个请求运行。

2.了解MVCC(多版本并发控制)

PostgreSQL 的 MVCC 通过保留不同版本的行来允许并发事务。以下是如何使用事务在 Golang 中演示 MVCC 行为的示例:

go get github.com/gin-gonic/gin
go get gorm.io/gorm
go get gorm.io/driver/postgres
登录后复制
登录后复制
  • FOR UPDATE:在事务期间锁定所选行的更新,防止其他事务修改它,直到当前事务完成。
  • 这确保了并发访问期间的一致性,展示了 MVCC 如何允许并发读取但锁定行以进行更新。

3. 将窗口函数与 GORM 结合使用

窗口函数用于对与当前行相关的一组表行执行计算。以下是使用窗口函数计算每位作者借阅书籍的运行总数的示例:

mkdir library-api
cd library-api
go mod init library-api
登录后复制
登录后复制
登录后复制
  • SUM(COUNT(bl.id)) OVER (PARTITION BY a.id ORDER BY bl.borrowed_at):一个窗口函数,计算每个作者借阅书籍的运行总数,按borrowed_at日期排序。
  • 这可以提供见解,例如每个作者的借阅趋势如何随时间变化。

以上是Golang RESTful API 与 Gin、Gorm、PostgreSQL的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1672
14
CakePHP 教程
1428
52
Laravel 教程
1332
25
PHP教程
1276
29
C# 教程
1256
24
Golang vs. Python:性能和可伸缩性 Golang vs. Python:性能和可伸缩性 Apr 19, 2025 am 12:18 AM

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

Golang和C:并发与原始速度 Golang和C:并发与原始速度 Apr 21, 2025 am 12:16 AM

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

开始GO:初学者指南 开始GO:初学者指南 Apr 26, 2025 am 12:21 AM

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang vs.C:性能和速度比较 Golang vs.C:性能和速度比较 Apr 21, 2025 am 12:13 AM

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

Golang的影响:速度,效率和简单性 Golang的影响:速度,效率和简单性 Apr 14, 2025 am 12:11 AM

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。

Golang vs. Python:主要差异和相似之处 Golang vs. Python:主要差异和相似之处 Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和C:性能的权衡 Golang和C:性能的权衡 Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

表演竞赛:Golang vs.C 表演竞赛:Golang vs.C Apr 16, 2025 am 12:07 AM

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。

See all articles