如何使用 Go Fiber 和 Gorm ORM 构建 REST API
概述
过去我写过几篇关于如何与关系型数据库交互的文章,但它们都是面向 JavaScript 和 TypeScript 社区的。所以本周我将和大家分享如何创建一个简单的 API,并对数据库中的特定表执行 CRUD 操作,这次是用 Go 语言。
在本文中,我们将使用Fiber框架,就像我过去用 Golang 写的其他文章一样,它使用起来非常简单,具有良好的抽象层,并且包含了创建 API 所需的一切。
关于与数据库的交互,我决定使用 ORM 来简化整个过程,使其更加直观。因此,我决定使用Gorm,在我看来,它是 Go 世界中最流行的 ORM,并且具有丰富的功能。
让我们开始编程吧
在今天的示例中,我们将只安装以下三个依赖项:
go get github.com/gofiber/fiber/v2
go get gorm.io/gorm
go get gorm.io/driver/mysql
如您所见,在本例中,我安装了 MySQL 驱动程序,因为我在 docker 容器中运行的数据库是 MariaDB,但是也有 PostgreSQL 和 SQLite 的驱动程序可用。
现在让我们从定义实体开始,它将总共有四个属性:
Name狗的名字Age我们四条腿朋友的年龄Breed我们朋友的比赛IsGoodBoy无论我们的朋友是否是个好孩子
与以下内容类似:
// @/entities/dog.go
package entities
import "gorm.io/gorm"
type Dog struct {
gorm.Model
Name string `json:"name"`
Breed string `json:"breed"`
Age int `json:"age"`
IsGoodBoy bool `json:"isGoodBoy" gorm:"default:true"`
}
现在我们可以开始配置数据库连接了。这里我打算创建一个名为 `connection` 的函数Connect(),它负责初始化连接,同时还会负责执行数据库迁移。具体操作如下:
// @/config/database.go
package config
import (
"github.com/FranciscoMendes10866/gorm/entities"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var Database *gorm.DB
var DATABASE_URI string = "root:root@tcp(localhost:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
func Connect() error {
var err error
Database, err = gorm.Open(mysql.Open(DATABASE_URI), &gorm.Config{
SkipDefaultTransaction: true,
PrepareStmt: true,
})
if err != nil {
panic(err)
}
Database.AutoMigrate(&entities.Dog{})
return nil
}
现在我们已经定义了实体并配置了数据库连接,可以开始编写处理程序了。每个处理程序都对应 API 中的一个路由,因此每个处理程序只负责执行一个操作。首先,让我们获取数据库表中的所有记录。
// @/handlers/dog.go
package handlers
import (
"github.com/FranciscoMendes10866/gorm/config"
"github.com/FranciscoMendes10866/gorm/entities"
"github.com/gofiber/fiber/v2"
)
func GetDogs(c *fiber.Ctx) error {
var dogs []entities.Dog
config.Database.Find(&dogs)
return c.Status(200).JSON(dogs)
}
// ...
现在,让我们根据id请求参数中发送的参数获取一条记录。
// @/handlers/dog.go
package handlers
// ...
func GetDog(c *fiber.Ctx) error {
id := c.Params("id")
var dog entities.Dog
result := config.Database.Find(&dog, id)
if result.RowsAffected == 0 {
return c.SendStatus(404)
}
return c.Status(200).JSON(&dog)
}
// ...
现在我们可以获取所有记录,也可以只获取一条记录。但我们缺少向数据库表中插入新记录的功能。
// @/handlers/dog.go
package handlers
// ...
func AddDog(c *fiber.Ctx) error {
dog := new(entities.Dog)
if err := c.BodyParser(dog); err != nil {
return c.Status(503).SendString(err.Error())
}
config.Database.Create(&dog)
return c.Status(201).JSON(dog)
}
// ...
我们还需要添加更新数据库中现有记录的功能。与我们已经实现的功能类似,让我们使用id参数来更新特定的记录。
// @/handlers/dog.go
package handlers
// ...
func UpdateDog(c *fiber.Ctx) error {
dog := new(entities.Dog)
id := c.Params("id")
if err := c.BodyParser(dog); err != nil {
return c.Status(503).SendString(err.Error())
}
config.Database.Where("id = ?", id).Updates(&dog)
return c.Status(200).JSON(dog)
}
// ...
最后,我们需要删除一条特定的记录,我们将再次使用 id 参数从数据库中删除该特定记录。
// @/handlers/dog.go
package handlers
// ...
func RemoveDog(c *fiber.Ctx) error {
id := c.Params("id")
var dog entities.Dog
result := config.Database.Delete(&dog, id)
if result.RowsAffected == 0 {
return c.SendStatus(404)
}
return c.SendStatus(200)
}
// ...
现在我们只需要创建主文件,该文件将负责初始化与数据库的连接,并在其中定义 API 路由,并将每个路由关联一个处理程序。
// @/main.go
package main
import (
"log"
"github.com/FranciscoMendes10866/gorm/config"
"github.com/FranciscoMendes10866/gorm/handlers"
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
config.Connect()
app.Get("/dogs", handlers.GetDogs)
app.Get("/dogs/:id", handlers.GetDog)
app.Post("/dogs", handlers.AddDog)
app.Put("/dogs/:id", handlers.UpdateDog)
app.Delete("/dogs/:id", handlers.RemoveDog)
log.Fatal(app.Listen(":3000"))
}
结论
和往常一样,希望您觉得这篇文章有趣。如果您发现文章中有任何错误,请在评论区指出。🧑🏻💻
祝你今天过得愉快!🚨
文章来源:https://dev.to/franciscomendes10866/how-to-build-rest-api-using-go- Fiber-and-gorm-orm-2jbe