可选参数示例
本项目演示了如何在 Go 应用中使用 Fiber 框架处理可选参数。
先决条件
请确保已安装以下内容
- Golang
- Fiber 包
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/optional-parameter -
安装依赖
go get
运行应用
- 启动应用
go run main.go
示例
以下是如何在 Fiber 应用中处理可选参数的示例
package main
import (
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
app.Get("/user/:id?", func(c *fiber.Ctx) error {
id := c.Params("id", "defaultID")
return c.SendString("User ID: " + id)
})
app.Listen(":3000")
}
在此示例中
- 路由中的
:id?
参数是可选的。 - 如果未提供
id
参数,则默认值为"defaultID"
。