搜索
首页后端开发Golang使用 Go Fiber 构建 RESTful API:受 Express 启发的样板

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate
一个样板/入门项目,用于使用 Go、Fiber 和 PostgreSQL 快速构建 RESTful API。受到 Express 样板的启发。

该应用程序具有许多内置功能,例如使用 JWT 和 Google OAuth2 进行身份验证、请求验证、单元和集成测试、docker 支持、API 文档、分页等。有关更多详细信息,请查看下面的功能列表。

目录

  • 特点
  • 命令
  • 环境变量
  • 项目结构
  • API 文档
  • 错误处理
  • 验证
  • 身份验证
  • 授权
  • 记录
  • Linting
  • 贡献

特征

  • SQL 数据库:使用 Gorm 进行 PostgreSQL 对象关系映射
  • 数据库迁移:使用 golang-migrate
  • 验证:使用包验证器请求数据验证
  • 日志记录:使用 Logrus 和 Fiber-Logger
  • 测试:使用 Testify 进行单元和集成测试,并使用 gotestsum 进行格式化测试输出
  • 错误处理:集中式错误处理机制
  • API 文档:使用 Swag 和 Swagger
  • 发送电子邮件:使用 Gomail
  • 环境变量:使用Viper
  • 安全性:使用 Fiber-Helmet 设置安全 HTTP 标头
  • CORS:使用 Fiber-CORS 启用跨源资源共享
  • 压缩:使用 Fiber-compress 进行 gzip 压缩
  • Docker 支持
  • Linting:使用 golangci-lint

命令

克隆存储库:


git clone --depth 1 https://github.com/indrayyana/go-fiber-boilerplate.git
cd go-fiber-boilerplate
rm -rf ./.git


安装依赖项:


go mod tidy


设置环境变量:


cp .env.example .env

# open .env and modify the environment variables (if needed)


本地运行:


make start


或者通过实时重新加载运行:


air


注意:
确保您已安装 Air。
看 ?如何安装Air

测试:


# run all tests
make tests

# run all tests with gotestsum format
make testsum

# run test for the selected function name
make tests-TestUserModel


码头工人:


# run docker container
make docker

# run all tests in a docker container
make docker-test


检查:


# run lint
make lint


大摇大摆:


# generate the swagger documentation
make swagger


迁移:


# Create migration
make migration-<table-name>

# Example for table users
make migration-users


</table-name>

# run migration up in local
make migrate-up

# run migration down in local
make migrate-down

# run migration up in docker container
make migrate-docker-up

# run migration down all in docker container
make migrate-docker-down


环境变量

环境变量可以在.env文件中找到并修改。它们具有以下默认值:


# server configuration
# Env value : prod || dev
APP_ENV=dev
APP_HOST=0.0.0.0
APP_PORT=3000

# database configuration
DB_HOST=postgresdb
DB_USER=postgres
DB_PASSWORD=thisisasamplepassword
DB_NAME=fiberdb
DB_PORT=5432

# JWT
# JWT secret key
JWT_SECRET=thisisasamplesecret
# Number of minutes after which an access token expires
JWT_ACCESS_EXP_MINUTES=30
# Number of days after which a refresh token expires
JWT_REFRESH_EXP_DAYS=30
# Number of minutes after which a reset password token expires
JWT_RESET_PASSWORD_EXP_MINUTES=10
# Number of minutes after which a verify email token expires
JWT_VERIFY_EMAIL_EXP_MINUTES=10

# SMTP configuration options for the email service
SMTP_HOST=email-server
SMTP_PORT=587
SMTP_USERNAME=email-server-username
SMTP_PASSWORD=email-server-password
EMAIL_FROM=support@yourapp.com

# OAuth2 configuration
GOOGLE_CLIENT_ID=yourapps.googleusercontent.com
GOOGLE_CLIENT_SECRET=thisisasamplesecret
REDIRECT_URL=http://localhost:3000/v1/auth/google-callback


项目结构


src\
 |--config\         # Environment variables and configuration related things
 |--controller\     # Route controllers (controller layer)
 |--database\       # Database connection & migrations
 |--docs\           # Swagger files
 |--middleware\     # Custom fiber middlewares
 |--model\          # Postgres models (data layer)
 |--response\       # Response models
 |--router\         # Routes
 |--service\        # Business logic (service layer)
 |--utils\          # Utility classes and functions
 |--validation\     # Request data validation schemas
 |--main.go         # Fiber app


API文档

要查看可用 API 列表及其规范,请运行服务器并在浏览器中访问 http://localhost:3000/v1/docs。

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate

Building a RESTful API with Go Fiber: An Express-Inspired Boilerplate

此文档页面是使用控制器文件中作为注释编写的 Swag 定义自动生成的。

看到了吗?声明性注释格式。

API端点

可用路线列表:

授权路由:
POST /v1/auth/register - 注册
POST /v1/auth/login - 登录
POST /v1/auth/logout - 注销
POST /v1/auth/refresh-tokens - 刷新身份验证令牌
POST /v1/auth/forgot-password - 发送重置密码电子邮件
POST /v1/auth/reset-password - 重置密码
POST /v1/auth/send-verification-email - 发送验证电子邮件
POST /v1/auth/verify-email - 验证电子邮件
GET /v1/auth/google - 使用 google 帐户登录

用户路线:
POST /v1/users - 创建用户
GET /v1/users - 获取所有用户
GET /v1/users/:userId - 获取用户
PATCH /v1/users/:userId - 更新用户
DELETE /v1/users/:userId - 删除用户

错误处理

该应用程序包含自定义错误处理机制,可以在 src/utils/error.go 文件中找到。

它还利用 Fiber-Recover 中间件从处理程序堆栈中可能发生的任何恐慌中正常恢复,防止应用程序意外崩溃。

错误处理进程发送以下格式的错误响应:


{
  "code": 404,
  "status": "error",
  "message": "Not found"
}


Fiber 使用 Fiber.NewError() 提供自定义错误结构,您可以在其中指定响应代码和消息。然后可以从代码的任何部分返回此错误,Fiber 的 ErrorHandler 将自动捕获它。

例如,如果您尝试从数据库检索用户但未找到该用户,并且想要返回 404 错误,则代码可能如下所示:


func (s *userService) GetUserByID(c *fiber.Ctx, id string) {
    user := new(model.User)

    err := s.DB.WithContext(c.Context()).First(user, "id = ?", id).Error

    if errors.Is(err, gorm.ErrRecordNotFound) {
        return fiber.NewError(fiber.StatusNotFound, "User not found")
    }
}


Validation

Request data is validated using Package validator. Check the documentation for more details on how to write validations.

The validation schemas are defined in the src/validation directory and are used within the services by passing them to the validation logic. In this example, the CreateUser method in the userService uses the validation.CreateUser schema to validate incoming request data before processing it. The validation is handled by the Validate.Struct method, which checks the request data against the schema.


import (
    "app/src/model"
    "app/src/validation"

    "github.com/gofiber/fiber/v2"
)

func (s *userService) CreateUser(c *fiber.Ctx, req validation.CreateUser) (*model.User, error) {
    if err := s.Validate.Struct(&req); err != nil {
        return nil, err
    }
}


Authentication

To require authentication for certain routes, you can use the Auth middleware.


import (
    "app/src/controllers"
    m "app/src/middleware"
    "app/src/services"

    "github.com/gofiber/fiber/v2"
)

func SetupRoutes(app *fiber.App, u services.UserService, t services.TokenService) {
  userController := controllers.NewUserController(u, t)
    app.Post("/users", m.Auth(u), userController.CreateUser)
}


These routes require a valid JWT access token in the Authorization request header using the Bearer schema. If the request does not contain a valid access token, an Unauthorized (401) error is thrown.

Generating Access Tokens:

An access token can be generated by making a successful call to the register (POST /v1/auth/register) or login (POST /v1/auth/login) endpoints. The response of these endpoints also contains refresh tokens (explained below).

An access token is valid for 30 minutes. You can modify this expiration time by changing the JWT_ACCESS_EXP_MINUTES environment variable in the .env file.

Refreshing Access Tokens:

After the access token expires, a new access token can be generated, by making a call to the refresh token endpoint (POST /v1/auth/refresh-tokens) and sending along a valid refresh token in the request body. This call returns a new access token and a new refresh token.

A refresh token is valid for 30 days. You can modify this expiration time by changing the JWT_REFRESH_EXP_DAYS environment variable in the .env file.

Authorization

The Auth middleware can also be used to require certain rights/permissions to access a route.


import (
    "app/src/controllers"
    m "app/src/middleware"
    "app/src/services"

    "github.com/gofiber/fiber/v2"
)

func SetupRoutes(app *fiber.App, u services.UserService, t services.TokenService) {
  userController := controllers.NewUserController(u, t)
    app.Post("/users", m.Auth(u, "manageUsers"), userController.CreateUser)
}


In the example above, an authenticated user can access this route only if that user has the manageUsers permission.

The permissions are role-based. You can view the permissions/rights of each role in the src/config/roles.go file.

If the user making the request does not have the required permissions to access this route, a Forbidden (403) error is thrown.

Logging

Import the logger from src/utils/logrus.go. It is using the Logrus logging library.

Logging should be done according to the following severity levels (ascending order from most important to least important):


import "app/src/utils"

utils.Log.Panic('message') // Calls panic() after logging
utils.Log.Fatal('message'); // Calls os.Exit(1) after logging
utils.Log.Error('message');
utils.Log.Warn('message');
utils.Log.Info('message');
utils.Log.Debug('message');
utils.Log.Trace('message');


Note:
API request information (request url, response code, timestamp, etc.) are also automatically logged (using Fiber-Logger).

Linting

Linting is done using golangci-lint

See ? How to install golangci-lint

To modify the golangci-lint configuration, update the .golangci.yml file.

Contributing

Contributions are more than welcome! Please check out the contributing guide.

If you find this boilerplate useful, consider giving it a star! ⭐

The full source code is available at the GitHub link below:

https://github.com/indrayyana/go-fiber-boilerplate

以上是使用 Go Fiber 构建 RESTful API:受 Express 启发的样板的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C和Golang:表演至关重要时C和Golang:表演至关重要时Apr 13, 2025 am 12:11 AM

C 更适合需要直接控制硬件资源和高性能优化的场景,而Golang更适合需要快速开发和高并发处理的场景。1.C 的优势在于其接近硬件的特性和高度的优化能力,适合游戏开发等高性能需求。2.Golang的优势在于其简洁的语法和天然的并发支持,适合高并发服务开发。

Golang行动:现实世界中的示例和应用程序Golang行动:现实世界中的示例和应用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性着称。 1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go编程语言解释了Golang:Go编程语言解释了Apr 10, 2025 am 11:18 AM

Go语言的核心特性包括垃圾回收、静态链接和并发支持。1.Go语言的并发模型通过goroutine和channel实现高效并发编程。2.接口和多态性通过实现接口方法,使得不同类型可以统一处理。3.基本用法展示了函数定义和调用的高效性。4.高级用法中,切片提供了动态调整大小的强大功能。5.常见错误如竞态条件可以通过gotest-race检测并解决。6.性能优化通过sync.Pool重用对象,减少垃圾回收压力。

Golang的目的:建立高效且可扩展的系统Golang的目的:建立高效且可扩展的系统Apr 09, 2025 pm 05:17 PM

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

SQL排序中ORDER BY语句结果为何有时看似随机?SQL排序中ORDER BY语句结果为何有时看似随机?Apr 02, 2025 pm 05:24 PM

关于SQL查询结果排序的疑惑学习SQL的过程中,常常会遇到一些令人困惑的问题。最近,笔者在阅读《MICK-SQL基础�...

技术栈收敛是否仅仅是技术栈选型的过程?技术栈收敛是否仅仅是技术栈选型的过程?Apr 02, 2025 pm 05:21 PM

技术栈收敛与技术选型的关系在软件开发中,技术栈的选择和管理是一个非常关键的问题。最近,有读者提出了...

如何在Go语言中使用反射对比并处理三个结构体的差异?如何在Go语言中使用反射对比并处理三个结构体的差异?Apr 02, 2025 pm 05:15 PM

Go语言中如何对比并处理三个结构体在Go语言编程中,有时需要对比两个结构体的差异,并将这些差异应用到第�...

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用