跳到主要内容
版本: v2.x

重写

Rewrite 中间件根据提供的规则重写 URL 路径。它有助于实现向后兼容性,或者只是创建更简洁、更具描述性的链接。

签名

func New(config ...Config) fiber.Handler

配置

属性类型描述默认值
下一个func(*fiber.Ctx) boolNext 定义了一个函数用于跳过中间件。nil
规则map[string]stringRules 定义了 URL 路径重写规则。星号中捕获的值可以通过索引检索。(必需)

示例

package main

import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/rewrite"
)

func main() {
app := fiber.New()

app.Use(rewrite.New(rewrite.Config{
Rules: map[string]string{
"/old": "/new",
"/old/*": "/new/$1",
},
}))

app.Get("/new", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
app.Get("/new/*", func(c *fiber.Ctx) error {
return c.SendString("Wildcard: " + c.Params("*"))
})

app.Listen(":3000")
}

测试

curl http://localhost:3000/old
curl http://localhost:3000/old/hello