项目实战:使用 Fiber + Gorm 构建 Rest API

开发 项目管理
Fiber 作为一个新的 Go 框架,似乎受追捧程度很高,Star 数飙升很快。不知道这是不是表明,不少 JS/Node 爱好者开始尝试学习 Go 了,对 Go 是好事。

大家好,我是程序员幽鬼。

Fiber 作为一个新的 Go 框架,似乎受追捧程度很高,Star 数飙升很快。不知道这是不是表明,不少 JS/Node 爱好者开始尝试学习 Go 了,对 Go 是好事。

今天这篇文章介绍如何使用 Fiber + Gorm 构建 REST API。

1 概览

在这篇文章中,我们将使用 Fiber[1] 框架,它使用起来非常简单,有一个很好的抽象层,并且包含我们创建 API 所需的一切。

关于与数据库的交互,我决定使用 ORM 来使整个过程更简单、更直观,因此我决定使用Gorm[2],在我看来,Gorm[3] 是 Go 世界中最受欢迎的 ORM,并且特性很多。

2 准备工作

本文基于 Go1.17.5。

在本地创建一个目录 fibergorm,然后进入该目录执行如下命令:

  1. $ go mod init github.com/programmerug/fibergorm 
  2. go: creating new go.mod: module github.com/programmerug/fibergorm 

接着执行如下命令,安装我们需要的依赖:(这个先不执行,之后通过 go mod tidy 安装)

  1. go get github.com/gofiber/fiber/v2 
  2. go get gorm.io/gorm 

为了方便,本教程中,我们使用 SQLite,因为使用了 Gorm,所以哪种关系型数据库对核心代码没有什么影响。

3 开始编码

本文以人类的朋友——狗为例。

先从定义实体开始,它总共有四个属性:

  • Name - 狗的名字
  • Age - 狗的年龄
  • Breed - 狗的种族(类型)
  • IsGoodBoy - 狗是否是个好孩子

类似以下内容:

  1. // 文件名:entities/dog.go 
  2. package entities 
  3.  
  4. import "gorm.io/gorm" 
  5.  
  6. type Dog struct { 
  7.     gorm.Model 
  8.     Name      string `json:"name"
  9.     Age       int    `json:"age"
  10.     Breed     string `json:"breed"
  11.     IsGoodBoy bool   `json:"is_good_boy" gorm:"default:true"

注意其中的内嵌类型 gorm.Model,它只是定义了一些通用的字段。

  1. type Model struct { 
  2.     ID        uint `gorm:"primarykey"
  3.     CreatedAt time.Time 
  4.     UpdatedAt time.Time 
  5.     DeletedAt DeletedAt `gorm:"index"

因此,我们完全可以自己选择是否要嵌入 gorm.Model。

接着,我们配置与数据库的连接。一般我喜欢创建一个名为 Connect() 的函数,它负责初始化连接,此外还负责在我们的数据库中执行迁移(migration),即生成表结构:

  1. // 文件名:config/database.go 
  2. package config 
  3.  
  4. import ( 
  5.     "github.com/programmerug/fibergorm/entities" 
  6.     "gorm.io/driver/sqlite" 
  7.     "gorm.io/gorm" 
  8.  
  9. var Database *gorm.DB 
  10.  
  11. func Connect() error { 
  12.     var err error 
  13.  
  14.     Database, err = gorm.Open(sqlite.Open("fibergorm.db"), &gorm.Config{}) 
  15.  
  16.     if err != nil { 
  17.         panic(err) 
  18.     } 
  19.  
  20.     Database.AutoMigrate(&entities.Dog{}) 
  21.  
  22.     return nil 
  • fibergorm.db 是最后生成的数据库文件
  • 在程序启动时,需要调用 Connect 函数

现在已经定义了实体并配置了到数据库的连接,我们可以开始处理我们的处理程序。我们的每个处理程序都将对应来自 API 的一个路由,每个处理程序只负责执行一个操作。首先让我们获取数据库表中的所有记录。

  1. // 文件名:handlers/dog.go 
  2. package handlers 
  3.  
  4. import ( 
  5.     "github.com/gofiber/fiber/v2" 
  6.     "github.com/programmerug/fibergorm/config" 
  7.     "github.com/programmerug/fibergorm/entities" 
  8.  
  9. func GetDogs(c *fiber.Ctx) error { 
  10.     var dogs []entities.Dog 
  11.  
  12.     config.Database.Find(&dogs) 
  13.     return c.Status(200).JSON(dogs) 
  14.  
  15. // ... 

现在根据将在请求参数中发送的 id 参数获取一条记录。

  1. // 文件名:handlers/dog.go 
  2. package handlers 
  3.  
  4. // ... 
  5.  
  6. func GetDog(c *fiber.Ctx) error { 
  7.     id := c.Params("id"
  8.     var dog entities.Dog 
  9.  
  10.     result := config.Database.Find(&dog, id) 
  11.  
  12.     if result.RowsAffected == 0 { 
  13.         return c.SendStatus(404) 
  14.     } 
  15.  
  16.     return c.Status(200).JSON(&dog) 
  17.  
  18. // ... 

现在我们可以得到所有的记录和根据 id 获取一条记录。但缺乏在数据库表中插入新记录的功能。

  1. // 文件名:handlers/dog.go 
  2. package handlers 
  3.  
  4. // ... 
  5.  
  6. func AddDog(c *fiber.Ctx) error { 
  7.     dog := new(entities.Dog) 
  8.  
  9.     if err := c.BodyParser(dog); err != nil { 
  10.         return c.Status(503).SendString(err.Error()) 
  11.     } 
  12.  
  13.     config.Database.Create(&dog) 
  14.     return c.Status(201).JSON(dog) 
  15.  
  16. // ... 

我们还需要添加更新数据库中现有记录的功能。与我们已经实现的类似,使用id参数来更新特定记录。

  1. // 文件名:handlers/dog.go 
  2. package handlers 
  3.  
  4. // ... 
  5.  
  6. func UpdateDog(c *fiber.Ctx) error { 
  7.     dog := new(entities.Dog) 
  8.     id := c.Params("id"
  9.  
  10.     if err := c.BodyParser(dog); err != nil { 
  11.         return c.Status(503).SendString(err.Error()) 
  12.     } 
  13.  
  14.     config.Database.Where("id = ?", id).Updates(&dog) 
  15.     return c.Status(200).JSON(dog) 
  16.  
  17. // ... 
  18. 最后,我们需要删除特定记录,再次使 

最后,我们需要删除特定记录,再次使用 id 参数从我们的数据库中删除特定记录。

  1. // 文件名:handlers/dog.go 
  2. package handlers 
  3.  
  4. // ... 
  5.  
  6. func RemoveDog(c *fiber.Ctx) error { 
  7.     id := c.Params("id"
  8.     var dog entities.Dog 
  9.  
  10.     result := config.Database.Delete(&dog, id) 
  11.  
  12.     if result.RowsAffected == 0 { 
  13.         return c.SendStatus(404) 
  14.     } 
  15.  
  16.     return c.SendStatus(200) 
  17.  
  18. // ... 

现在只需要创建我们的 main 文件,该文件将负责初始化与数据库的连接以及我们的 API 路由将在何处定义,并且将处理程序与它们进行关联绑定。

  1. // 文件名:main.go 
  2. package main 
  3.  
  4. import ( 
  5.     "log" 
  6.  
  7.     "github.com/gofiber/fiber/v2" 
  8.     "github.com/programmerug/fibergorm/config" 
  9.     "github.com/programmerug/fibergorm/handlers" 
  10.  
  11. func main() { 
  12.     app := fiber.New() 
  13.  
  14.     config.Connect() 
  15.  
  16.     app.Get("/dogs", handlers.GetDogs) 
  17.     app.Get("/dogs/:id", handlers.GetDog) 
  18.     app.Post("/dogs", handlers.AddDog) 
  19.     app.Put("/dogs/:id", handlers.UpdateDog) 
  20.     app.Delete("/dogs/:id", handlers.RemoveDog) 
  21.  
  22.     log.Fatal(app.Listen(":3000")) 

至此,我们完成了一个简单应用的 CRUD。涉及到 fiber 和 gorm 的 API 你应该查阅相关文档进一步了解。

最终,项目目录如下:

  1. ├── config 
  2. │   └── database.go 
  3. ├── entities 
  4. │   └── dog.go 
  5. ├── fibergorm.db 
  6. ├── go.mod 
  7. ├── go.sum 
  8. ├── handlers 
  9. │   └── dog.go 
  10. └── main.go 

执行 go run main.go:

  1. $ go run main.go 
  2.  
  3.  ┌───────────────────────────────────────────────────┐ 
  4.  │                   Fiber v2.24.0                   │ 
  5.  │               http://127.0.0.1:3000               │ 
  6.  │       (bound on host 0.0.0.0 and port 3000)       │ 
  7.  │                                                   │ 
  8.  │ Handlers ............. 7  Processes ........... 1 │ 
  9.  │ Prefork ....... Disabled  PID ............. 89910 │ 
  10.  └───────────────────────────────────────────────────┘ 

借助 postman、curl 之类的工具验证接口的正确性。

因为 fiber Ctx 的 BodyParser 能够解析 Context-Type 值是:application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data 等的数据,所以,验证 AddDog 的可以采用你喜欢的 Content-Type。

  1. curl --location --request POST 'http://127.0.0.1:3000/dogs' \ 
  2. --header 'Content-Type: application/json' \ 
  3. --data '{name:"旺财",age:3,breed:"狼狗",is_good_boy:true}' 

可以通过下载 https://sqlitebrowser.org/dl/ 这个 SQLite 工具查看数据是否保存成功。

细心的读者可能会发现,生成的数据表字段顺序是根据 Dog 中的字段定义顺序确定的。有强迫症的人可能接受不了,因此实际中你可以不嵌入 gorm.Model,而是自己定义相关字段。

总结

本文实现了 CRUD 的功能,希望大家实际动手,这样才能够真正掌握。

本文参考 https://dev.to/franciscomendes10866/how-to-build-rest-api-using-go-fiber-and-gorm-orm-2jbe。

本文完整代码:https://github.com/programmerug/fibergorm。

参考资料

[1]Fiber: https://gofiber.io/

[2]Gorm: https://gorm.io/

[3]Gorm: https://gorm.io/

 

责任编辑:武晓燕 来源: 幽鬼
相关推荐

2022-02-09 14:36:25

GoMongoDBFiber

2023-04-18 15:18:10

2022-05-31 07:40:41

ArctypeFeather.jsSQLite

2020-07-07 07:00:00

Spring WebFREST APIReactive AP

2023-09-21 11:20:46

2023-05-11 12:40:00

Spring控制器HTTP

2023-12-06 07:13:16

RESTAPI客户端

2021-12-02 16:20:18

RabbitMQAPIRest

2012-08-28 11:12:37

IBMdW

2021-05-17 09:27:07

项目实战优化项目构建时间

2024-01-09 09:09:45

RESTGraphQL

2023-11-17 12:04:39

GORM并发

2023-11-06 12:00:04

GORM

2023-01-10 14:11:26

2021-11-22 09:00:00

后端开发CMS

2024-01-30 08:58:22

JenkinsGit流程

2011-10-27 16:24:48

API

2022-02-10 23:38:23

API架构设计

2023-11-04 15:46:03

GORMGo

2013-07-18 17:00:12

Gradle构建AndAndroid开发Android学习
点赞
收藏

51CTO技术栈公众号