mirror of https://github.com/gofiber/fiber.git
parent
960b652587
commit
956b66d95f
|
@ -110,7 +110,7 @@ import "github.com/gofiber/fiber/v2"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
||||
|
@ -178,31 +178,31 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
})
|
||||
|
||||
// GET /flights/LAX-SFO
|
||||
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
|
||||
app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
|
||||
return c.SendString(msg) // => 💸 From: LAX, To: SFO
|
||||
})
|
||||
|
||||
// GET /dictionary.txt
|
||||
app.Get("/:file.:ext", func(c *fiber.Ctx) error {
|
||||
app.Get("/:file.:ext", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
|
||||
return c.SendString(msg) // => 📃 dictionary.txt
|
||||
})
|
||||
|
||||
// GET /john/75
|
||||
app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name/:age/:gender?", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
|
||||
return c.SendString(msg) // => 👴 john is 75 years old
|
||||
})
|
||||
|
||||
// GET /john
|
||||
app.Get("/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
|
||||
return c.SendString(msg) // => Hello john 👋!
|
||||
})
|
||||
|
@ -219,7 +219,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
}).Name("api")
|
||||
|
@ -271,19 +271,19 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// Match any route
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
fmt.Println("🥇 First handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥈 Second handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// GET /api/list
|
||||
app.Get("/api/list", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/list", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥉 Last handler")
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
@ -323,7 +323,7 @@ func main() {
|
|||
})
|
||||
|
||||
// Və indi `./views/home.pug` template-i bu şəkildə çağıra bilərsiniz:
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("home", fiber.Map{
|
||||
"title": "Homepage",
|
||||
"year": 1999,
|
||||
|
@ -339,12 +339,12 @@ func main() {
|
|||
📖 [Group](https://docs.gofiber.io/api/app#group)
|
||||
|
||||
```go
|
||||
func middleware(c *fiber.Ctx) error {
|
||||
func middleware(c fiber.Ctx) error {
|
||||
fmt.Println("Don't mind me!")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
return c.SendString(c.Path())
|
||||
}
|
||||
|
||||
|
@ -433,16 +433,16 @@ func main() {
|
|||
|
||||
app.Static("/", "./public")
|
||||
|
||||
app.Get("/demo", func(c *fiber.Ctx) error {
|
||||
app.Get("/demo", func(c fiber.Ctx) error {
|
||||
return c.SendString("This is a demo!")
|
||||
})
|
||||
|
||||
app.Post("/register", func(c *fiber.Ctx) error {
|
||||
app.Post("/register", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome!")
|
||||
})
|
||||
|
||||
// Sonuncu middleware-in hər şeyə uyğunlaşdırılması
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.SendStatus(404)
|
||||
// => 404 "Not Found"
|
||||
})
|
||||
|
@ -464,12 +464,12 @@ type User struct {
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/user", func(c *fiber.Ctx) error {
|
||||
app.Get("/user", func(c fiber.Ctx) error {
|
||||
return c.JSON(&User{"John", 20})
|
||||
// => {"name":"John", "age":20}
|
||||
})
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) error {
|
||||
app.Get("/json", func(c fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "Hi John!",
|
||||
|
@ -528,7 +528,7 @@ import (
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/sse", func(c *fiber.Ctx) error {
|
||||
app.Get("/sse", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
|
@ -571,7 +571,7 @@ func main() {
|
|||
|
||||
app.Use(recover.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("normally this would crash your app")
|
||||
})
|
||||
|
||||
|
|
|
@ -111,7 +111,7 @@ import "github.com/gofiber/fiber/v2"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
||||
|
@ -178,31 +178,31 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
})
|
||||
|
||||
// GET /flights/LAX-SFO
|
||||
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
|
||||
app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
|
||||
return c.SendString(msg) // => 💸 From: LAX, To: SFO
|
||||
})
|
||||
|
||||
// GET /dictionary.txt
|
||||
app.Get("/:file.:ext", func(c *fiber.Ctx) error {
|
||||
app.Get("/:file.:ext", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
|
||||
return c.SendString(msg) // => 📃 dictionary.txt
|
||||
})
|
||||
|
||||
// GET /john/75
|
||||
app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name/:age/:gender?", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
|
||||
return c.SendString(msg) // => 👴 john is 75 years old
|
||||
})
|
||||
|
||||
// GET /john
|
||||
app.Get("/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
|
||||
return c.SendString(msg) // => Hello john 👋!
|
||||
})
|
||||
|
@ -219,7 +219,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
}).Name("api")
|
||||
|
@ -271,19 +271,19 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// Match any route
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
fmt.Println("🥇 First handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥈 Second handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// GET /api/list
|
||||
app.Get("/api/list", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/list", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥉 Last handler")
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
@ -323,7 +323,7 @@ func main() {
|
|||
})
|
||||
|
||||
// And now, you can call template `./views/home.pug` like this:
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("home", fiber.Map{
|
||||
"title": "Homepage",
|
||||
"year": 1999,
|
||||
|
@ -339,12 +339,12 @@ func main() {
|
|||
📖 [Group](https://docs.gofiber.io/api/app#group)
|
||||
|
||||
```go
|
||||
func middleware(c *fiber.Ctx) error {
|
||||
func middleware(c fiber.Ctx) error {
|
||||
fmt.Println("Don't mind me!")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
return c.SendString(c.Path())
|
||||
}
|
||||
|
||||
|
@ -433,16 +433,16 @@ func main() {
|
|||
|
||||
app.Static("/", "./public")
|
||||
|
||||
app.Get("/demo", func(c *fiber.Ctx) error {
|
||||
app.Get("/demo", func(c fiber.Ctx) error {
|
||||
return c.SendString("This is a demo!")
|
||||
})
|
||||
|
||||
app.Post("/register", func(c *fiber.Ctx) error {
|
||||
app.Post("/register", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome!")
|
||||
})
|
||||
|
||||
// Last middleware to match anything
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.SendStatus(404)
|
||||
// => 404 "Not Found"
|
||||
})
|
||||
|
@ -464,12 +464,12 @@ type User struct {
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/user", func(c *fiber.Ctx) error {
|
||||
app.Get("/user", func(c fiber.Ctx) error {
|
||||
return c.JSON(&User{"John", 20})
|
||||
// => {"name":"John", "age":20}
|
||||
})
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) error {
|
||||
app.Get("/json", func(c fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "Hi John!",
|
||||
|
@ -528,7 +528,7 @@ import (
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/sse", func(c *fiber.Ctx) error {
|
||||
app.Get("/sse", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
|
@ -571,7 +571,7 @@ func main() {
|
|||
|
||||
app.Use(recover.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("normally this would crash your app")
|
||||
})
|
||||
|
||||
|
|
|
@ -112,7 +112,7 @@ import "github.com/gofiber/fiber/v2"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
||||
|
@ -181,31 +181,31 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
})
|
||||
|
||||
// GET /flights/LAX-SFO
|
||||
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
|
||||
app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
|
||||
return c.SendString(msg) // => 💸 From: LAX, To: SFO
|
||||
})
|
||||
|
||||
// GET /dictionary.txt
|
||||
app.Get("/:file.:ext", func(c *fiber.Ctx) error {
|
||||
app.Get("/:file.:ext", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
|
||||
return c.SendString(msg) // => 📃 dictionary.txt
|
||||
})
|
||||
|
||||
// GET /john/75
|
||||
app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name/:age/:gender?", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
|
||||
return c.SendString(msg) // => 👴 john is 75 years old
|
||||
})
|
||||
|
||||
// GET /john
|
||||
app.Get("/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
|
||||
return c.SendString(msg) // => Hello john 👋!
|
||||
})
|
||||
|
@ -222,7 +222,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
}).Name("api")
|
||||
|
@ -274,19 +274,19 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// Match any route
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
fmt.Println("🥇 First handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥈 Second handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// GET /api/list
|
||||
app.Get("/api/list", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/list", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥉 Last handler")
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
@ -324,7 +324,7 @@ func main() {
|
|||
})
|
||||
|
||||
// And now, you can call template `./views/home.pug` like this:
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("home", fiber.Map{
|
||||
"title": "Homepage",
|
||||
"year": 1999,
|
||||
|
@ -340,12 +340,12 @@ func main() {
|
|||
📖 [Group](https://docs.gofiber.io/api/app#group)
|
||||
|
||||
```go
|
||||
func middleware(c *fiber.Ctx) error {
|
||||
func middleware(c fiber.Ctx) error {
|
||||
fmt.Println("Don't mind me!")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
return c.SendString(c.Path())
|
||||
}
|
||||
|
||||
|
@ -433,16 +433,16 @@ func main() {
|
|||
|
||||
app.Static("/", "./public")
|
||||
|
||||
app.Get("/demo", func(c *fiber.Ctx) error {
|
||||
app.Get("/demo", func(c fiber.Ctx) error {
|
||||
return c.SendString("This is a demo!")
|
||||
})
|
||||
|
||||
app.Post("/register", func(c *fiber.Ctx) error {
|
||||
app.Post("/register", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome!")
|
||||
})
|
||||
|
||||
// Last middleware to match anything
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.SendStatus(404)
|
||||
// => 404 "Not Found"
|
||||
})
|
||||
|
@ -464,12 +464,12 @@ type User struct {
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/user", func(c *fiber.Ctx) error {
|
||||
app.Get("/user", func(c fiber.Ctx) error {
|
||||
return c.JSON(&User{"John", 20})
|
||||
// => {"name":"John", "age":20}
|
||||
})
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) error {
|
||||
app.Get("/json", func(c fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "Hi John!",
|
||||
|
@ -528,7 +528,7 @@ import (
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/sse", func(c *fiber.Ctx) error {
|
||||
app.Get("/sse", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
|
@ -571,7 +571,7 @@ func main() {
|
|||
|
||||
app.Use(recover.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("normally this would crash your app")
|
||||
})
|
||||
|
||||
|
|
|
@ -117,7 +117,7 @@ import "github.com/gofiber/fiber/v2"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
||||
|
@ -188,31 +188,31 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
})
|
||||
|
||||
// GET /flights/LAX-SFO
|
||||
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
|
||||
app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("💸 From: %s, To: %s", c.Params("from"), c.Params("to"))
|
||||
return c.SendString(msg) // => 💸 From: LAX, To: SFO
|
||||
})
|
||||
|
||||
// GET /dictionary.txt
|
||||
app.Get("/:file.:ext", func(c *fiber.Ctx) error {
|
||||
app.Get("/:file.:ext", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("📃 %s.%s", c.Params("file"), c.Params("ext"))
|
||||
return c.SendString(msg) // => 📃 dictionary.txt
|
||||
})
|
||||
|
||||
// GET /john/75
|
||||
app.Get("/:name/:age/:gender?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name/:age/:gender?", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("👴 %s is %s years old", c.Params("name"), c.Params("age"))
|
||||
return c.SendString(msg) // => 👴 john is 75 years old
|
||||
})
|
||||
|
||||
// GET /john
|
||||
app.Get("/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("Hello, %s 👋!", c.Params("name"))
|
||||
return c.SendString(msg) // => Hello john 👋!
|
||||
})
|
||||
|
@ -228,7 +228,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// GET /api/register
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("✋ %s", c.Params("*"))
|
||||
return c.SendString(msg) // => ✋ register
|
||||
}).Name("api")
|
||||
|
@ -278,19 +278,19 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
// Match any route
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
fmt.Println("🥇 First handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match all routes starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥈 Second handler")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// GET /api/list
|
||||
app.Get("/api/list", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/list", func(c fiber.Ctx) error {
|
||||
fmt.Println("🥉 Last handler")
|
||||
return c.SendString("Hello, World 👋!")
|
||||
})
|
||||
|
@ -329,7 +329,7 @@ func main() {
|
|||
})
|
||||
|
||||
// And now, you can call template `./views/home.pug` like this:
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("home", fiber.Map{
|
||||
"title": "Homepage",
|
||||
"year": 1999,
|
||||
|
@ -345,12 +345,12 @@ func main() {
|
|||
📖 [Група](https://docs.gofiber.io/api/app#group)
|
||||
|
||||
```go
|
||||
func middleware(c *fiber.Ctx) error {
|
||||
func middleware(c fiber.Ctx) error {
|
||||
fmt.Println("Don't mind me!")
|
||||
return c.Next()
|
||||
}
|
||||
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
return c.SendString(c.Path())
|
||||
}
|
||||
|
||||
|
@ -438,16 +438,16 @@ func main() {
|
|||
|
||||
app.Static("/", "./public")
|
||||
|
||||
app.Get("/demo", func(c *fiber.Ctx) error {
|
||||
app.Get("/demo", func(c fiber.Ctx) error {
|
||||
return c.SendString("This is a demo!")
|
||||
})
|
||||
|
||||
app.Post("/register", func(c *fiber.Ctx) error {
|
||||
app.Post("/register", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome!")
|
||||
})
|
||||
|
||||
// Last middleware to match anything
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.SendStatus(404)
|
||||
// => 404 "Not Found"
|
||||
})
|
||||
|
@ -469,12 +469,12 @@ type User struct {
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/user", func(c *fiber.Ctx) error {
|
||||
app.Get("/user", func(c fiber.Ctx) error {
|
||||
return c.JSON(&User{"John", 20})
|
||||
// => {"name":"John", "age":20}
|
||||
})
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) error {
|
||||
app.Get("/json", func(c fiber.Ctx) error {
|
||||
return c.JSON(fiber.Map{
|
||||
"success": true,
|
||||
"message": "Hi John!",
|
||||
|
@ -533,7 +533,7 @@ import (
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/sse", func(c *fiber.Ctx) error {
|
||||
app.Get("/sse", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/event-stream")
|
||||
c.Set("Cache-Control", "no-cache")
|
||||
c.Set("Connection", "keep-alive")
|
||||
|
@ -576,7 +576,7 @@ func main() {
|
|||
|
||||
app.Use(recover.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("normally this would crash your app")
|
||||
})
|
||||
|
||||
|
|
|
@ -211,7 +211,7 @@ func main() {
|
|||
})
|
||||
|
||||
// GET /john
|
||||
app.Get("/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name", func(c fiber.Ctx) error {
|
||||
msg := fmt.Sprintf("哈囉,%s 👋!", c.Params("name"))
|
||||
return c.SendString(msg) // => 哈囉,john 👋!
|
||||
})
|
||||
|
|
|
@ -127,7 +127,7 @@ func main() {
|
|||
micro := fiber.New()
|
||||
app.Mount("/john", micro) // GET /john/doe -> 200 OK
|
||||
|
||||
micro.Get("/doe", func(c *fiber.Ctx) error {
|
||||
micro.Get("/doe", func(c fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
})
|
||||
|
||||
|
@ -261,7 +261,7 @@ func (app *App) Stack() [][]*Route
|
|||
```
|
||||
|
||||
```go title="Examples"
|
||||
var handler = func(c *fiber.Ctx) error { return nil }
|
||||
var handler = func(c fiber.Ctx) error { return nil }
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
@ -315,7 +315,7 @@ func (app *App) Name(name string) Router
|
|||
```
|
||||
|
||||
```go title="Examples"
|
||||
var handler = func(c *fiber.Ctx) error { return nil }
|
||||
var handler = func(c fiber.Ctx) error { return nil }
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
@ -417,7 +417,7 @@ func (app *App) GetRoute(name string) Route
|
|||
```
|
||||
|
||||
```go title="Examples"
|
||||
var handler = func(c *fiber.Ctx) error { return nil }
|
||||
var handler = func(c fiber.Ctx) error { return nil }
|
||||
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
|
@ -454,7 +454,7 @@ When filterUseOption equal to true, it will filter the routes registered by the
|
|||
```go title="Examples"
|
||||
func main() {
|
||||
app := fiber.New()
|
||||
app.Post("/", func (c *fiber.Ctx) error {
|
||||
app.Post("/", func (c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
}).Name("index")
|
||||
data, _ := json.MarshalIndent(app.GetRoutes(true), "", " ")
|
||||
|
@ -627,7 +627,7 @@ func (app *App) Test(req *http.Request, msTimeout ...int) (*http.Response, error
|
|||
|
||||
```go title="Examples"
|
||||
// Create route with GET method for test:
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
fmt.Println(c.BaseURL()) // => http://google.com
|
||||
fmt.Println(c.Get("X-Custom-Header")) // => hi
|
||||
|
||||
|
|
|
@ -22,7 +22,7 @@ func (c *Client) Delete(url string) *Agent
|
|||
Here we present a brief example demonstrating the simulation of a proxy using our `*fiber.Agent` methods.
|
||||
```go
|
||||
// Get something
|
||||
func getSomething(c *fiber.Ctx) (err error) {
|
||||
func getSomething(c fiber.Ctx) (err error) {
|
||||
agent := fiber.Get("<URL>")
|
||||
statusCode, body, errs := agent.Bytes()
|
||||
if len(errs) > 0 {
|
||||
|
@ -43,7 +43,7 @@ func getSomething(c *fiber.Ctx) (err error) {
|
|||
}
|
||||
|
||||
// Post something
|
||||
func createSomething(c *fiber.Ctx) (err error) {
|
||||
func createSomething(c fiber.Ctx) (err error) {
|
||||
agent := fiber.Post("<URL>")
|
||||
agent.Body(c.Body()) // set body received by request
|
||||
statusCode, body, errs := agent.Bytes()
|
||||
|
|
210
docs/api/ctx.md
210
docs/api/ctx.md
|
@ -26,7 +26,7 @@ func (c *Ctx) AcceptsLanguages(offers ...string) string
|
|||
```go title="Example"
|
||||
// Accept: text/html, application/json; q=0.8, text/plain; q=0.5; charset="utf-8"
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Accepts("html") // "html"
|
||||
c.Accepts("text/html") // "text/html"
|
||||
c.Accepts("json", "text") // "json"
|
||||
|
@ -41,7 +41,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go title="Example 2"
|
||||
// Accept: text/html, text/*, application/json, */*; q=0
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Accepts("text/plain", "application/json") // "application/json", due to specificity
|
||||
c.Accepts("application/json", "text/html") // "text/html", due to first match
|
||||
c.Accepts("image/png") // "", due to */* without q factor 0 is Not Acceptable
|
||||
|
@ -54,7 +54,7 @@ Media-Type parameters are supported.
|
|||
```go title="Example 3"
|
||||
// Accept: text/plain, application/json; version=1; foo=bar
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Extra parameters in the accept are ignored
|
||||
c.Accepts("text/plain;format=flowed") // "text/plain;format=flowed"
|
||||
|
||||
|
@ -69,7 +69,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go title="Example 4"
|
||||
// Accept: text/plain;format=flowed;q=0.9, text/plain
|
||||
// i.e., "I prefer text/plain;format=flowed less than other forms of text/plain"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Beware: the order in which offers are listed matters.
|
||||
// Although the client specified they prefer not to receive format=flowed,
|
||||
// the text/plain Accept matches with "text/plain;format=flowed" first, so it is returned.
|
||||
|
@ -87,7 +87,7 @@ Fiber provides similar functions for the other accept headers.
|
|||
// Accept-Encoding: gzip, compress;q=0.2
|
||||
// Accept-Language: en;q=0.8, nl, ru
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.AcceptsCharsets("utf-16", "iso-8859-1")
|
||||
// "iso-8859-1"
|
||||
|
||||
|
@ -111,14 +111,14 @@ func (c *Ctx) AllParams() map[string]string
|
|||
|
||||
```go title="Example"
|
||||
// GET http://example.com/user/fenny
|
||||
app.Get("/user/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:name", func(c fiber.Ctx) error {
|
||||
c.AllParams() // "{"name": "fenny"}"
|
||||
|
||||
// ...
|
||||
})
|
||||
|
||||
// GET http://example.com/user/fenny/123
|
||||
app.Get("/user/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/*", func(c fiber.Ctx) error {
|
||||
c.AllParams() // "{"*1": "fenny/123"}"
|
||||
|
||||
// ...
|
||||
|
@ -134,7 +134,7 @@ func (c *Ctx) App() *App
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/stack", func(c *fiber.Ctx) error {
|
||||
app.Get("/stack", func(c fiber.Ctx) error {
|
||||
return c.JSON(c.App().Stack())
|
||||
})
|
||||
```
|
||||
|
@ -152,7 +152,7 @@ func (c *Ctx) Append(field string, values ...string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Append("Link", "http://google.com", "http://localhost")
|
||||
// => Link: http://localhost, http://google.com
|
||||
|
||||
|
@ -172,7 +172,7 @@ func (c *Ctx) Attachment(filename ...string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Attachment()
|
||||
// => Content-Disposition: attachment
|
||||
|
||||
|
@ -236,7 +236,7 @@ func (c *Ctx) BaseURL() string
|
|||
```go title="Example"
|
||||
// GET https://example.com/page#chapter-1
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.BaseURL() // https://example.com
|
||||
// ...
|
||||
})
|
||||
|
@ -252,13 +252,13 @@ func (c *Ctx) Bind(vars Map) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
c.Bind(fiber.Map{
|
||||
"Title": "Hello, World!",
|
||||
})
|
||||
})
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("xxx.tmpl", fiber.Map{}) // Render will use Title variable
|
||||
})
|
||||
```
|
||||
|
@ -274,7 +274,7 @@ func (c *Ctx) BodyRaw() []byte
|
|||
```go title="Example"
|
||||
// curl -X POST http://localhost:8080 -d user=john
|
||||
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Get raw body from POST request:
|
||||
return c.Send(c.BodyRaw()) // []byte("user=john")
|
||||
})
|
||||
|
@ -294,7 +294,7 @@ func (c *Ctx) Body() []byte
|
|||
```go title="Example"
|
||||
// echo 'user=john' | gzip | curl -v -i --data-binary @- -H "Content-Encoding: gzip" http://localhost:8080
|
||||
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Decompress body from POST request based on the Content-Encoding and return the raw content:
|
||||
return c.Send(c.Body()) // []byte("user=john")
|
||||
})
|
||||
|
@ -328,7 +328,7 @@ type Person struct {
|
|||
Pass string `json:"pass" xml:"pass" form:"pass"`
|
||||
}
|
||||
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
p := new(Person)
|
||||
|
||||
if err := c.BodyParser(p); err != nil {
|
||||
|
@ -366,7 +366,7 @@ func (c *Ctx) ClearCookie(key ...string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Clears all cookies:
|
||||
c.ClearCookie()
|
||||
|
||||
|
@ -384,7 +384,7 @@ Web browsers and other compliant clients will only clear the cookie if the given
|
|||
:::
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/set", func(c *fiber.Ctx) error {
|
||||
app.Get("/set", func(c fiber.Ctx) error {
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "token",
|
||||
Value: "randomvalue",
|
||||
|
@ -396,7 +396,7 @@ app.Get("/set", func(c *fiber.Ctx) error {
|
|||
// ...
|
||||
})
|
||||
|
||||
app.Get("/delete", func(c *fiber.Ctx) error {
|
||||
app.Get("/delete", func(c fiber.Ctx) error {
|
||||
c.Cookie(&fiber.Cookie{
|
||||
Name: "token",
|
||||
// Set expiry date to the past
|
||||
|
@ -420,7 +420,7 @@ func (c *Ctx) ClientHelloInfo() *tls.ClientHelloInfo
|
|||
|
||||
```go title="Example"
|
||||
// GET http://example.com/hello
|
||||
app.Get("/hello", func(c *fiber.Ctx) error {
|
||||
app.Get("/hello", func(c fiber.Ctx) error {
|
||||
chi := c.ClientHelloInfo()
|
||||
// ...
|
||||
})
|
||||
|
@ -462,7 +462,7 @@ type Cookie struct {
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Create cookie
|
||||
cookie := new(fiber.Cookie)
|
||||
cookie.Name = "john"
|
||||
|
@ -492,7 +492,7 @@ type Person struct {
|
|||
Job bool `cookie:"job"`
|
||||
}
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
p := new(Person)
|
||||
|
||||
if err := c.CookieParser(p); err != nil {
|
||||
|
@ -516,7 +516,7 @@ func (c *Ctx) Cookies(key string, defaultValue ...string) string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Get cookie by key:
|
||||
c.Cookies("name") // "john"
|
||||
c.Cookies("empty", "doe") // "doe"
|
||||
|
@ -540,7 +540,7 @@ func (c *Ctx) Download(file string, filename ...string) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Download("./files/report-12345.pdf");
|
||||
// => Download report-12345.pdf
|
||||
|
||||
|
@ -611,7 +611,7 @@ func (c *Ctx) FormFile(key string) (*multipart.FileHeader, error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Get first file from form field "document":
|
||||
file, err := c.FormFile("document")
|
||||
|
||||
|
@ -629,7 +629,7 @@ func (c *Ctx) FormValue(key string, defaultValue ...string) string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Get first value from form field "name":
|
||||
c.FormValue("name")
|
||||
// => "john" or "" if not exist
|
||||
|
@ -666,7 +666,7 @@ func (c *Ctx) Get(key string, defaultValue ...string) string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Get("Content-Type") // "text/plain"
|
||||
c.Get("CoNtEnT-TypE") // "text/plain"
|
||||
c.Get("something", "john") // "john"
|
||||
|
@ -701,7 +701,7 @@ func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.GetRespHeader("X-Request-Id") // "8d7ad5e3-aaf3-450b-a241-2beb887efd54"
|
||||
c.GetRespHeader("Content-Type") // "text/plain"
|
||||
c.GetRespHeader("something", "john") // "john"
|
||||
|
@ -732,15 +732,15 @@ func (c *Ctx) GetRouteURL(routeName string, params Map) (string, error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Home page")
|
||||
}).Name("home")
|
||||
|
||||
app.Get("/user/:id", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:id", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("id"))
|
||||
}).Name("user.show")
|
||||
|
||||
app.Get("/test", func(c *fiber.Ctx) error {
|
||||
app.Get("/test", func(c fiber.Ctx) error {
|
||||
location, _ := c.GetRouteURL("user.show", fiber.Map{"id": 1})
|
||||
return c.SendString(location)
|
||||
})
|
||||
|
@ -759,7 +759,7 @@ func (c *Ctx) Hostname() string
|
|||
```go title="Example"
|
||||
// GET http://google.com/search
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Hostname() // "google.com"
|
||||
|
||||
// ...
|
||||
|
@ -778,7 +778,7 @@ func (c *Ctx) IP() string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.IP() // "127.0.0.1"
|
||||
|
||||
// ...
|
||||
|
@ -804,7 +804,7 @@ func (c *Ctx) IPs() []string
|
|||
```go title="Example"
|
||||
// X-Forwarded-For: proxy1, 127.0.0.1, proxy3
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.IPs() // ["proxy1", "127.0.0.1", "proxy3"]
|
||||
|
||||
// ...
|
||||
|
@ -830,7 +830,7 @@ func (c *Ctx) Is(extension string) bool
|
|||
```go title="Example"
|
||||
// Content-Type: text/html; charset=utf-8
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Is("html") // true
|
||||
c.Is(".html") // true
|
||||
c.Is("json") // false
|
||||
|
@ -849,7 +849,7 @@ func (c *Ctx) IsFromLocal() bool {
|
|||
|
||||
```go title="Example"
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// If request came from localhost, return true else return false
|
||||
c.IsFromLocal()
|
||||
|
||||
|
@ -875,7 +875,7 @@ type SomeStruct struct {
|
|||
Age uint8
|
||||
}
|
||||
|
||||
app.Get("/json", func(c *fiber.Ctx) error {
|
||||
app.Get("/json", func(c fiber.Ctx) error {
|
||||
// Create data struct:
|
||||
data := SomeStruct{
|
||||
Name: "Grame",
|
||||
|
@ -911,7 +911,7 @@ type SomeStruct struct {
|
|||
age uint8
|
||||
}
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Create data struct:
|
||||
data := SomeStruct{
|
||||
name: "Grame",
|
||||
|
@ -935,7 +935,7 @@ func (c *Ctx) Links(link ...string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Links(
|
||||
"http://api.example.com/users?page=2", "next",
|
||||
"http://api.example.com/users?page=5", "last",
|
||||
|
@ -970,12 +970,12 @@ type key int
|
|||
// instead of using this key directly.
|
||||
var userKey key
|
||||
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
c.Locals(userKey, "admin")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
app.Get("/admin", func(c *fiber.Ctx) error {
|
||||
app.Get("/admin", func(c fiber.Ctx) error {
|
||||
if c.Locals(userKey) == "admin" {
|
||||
return c.Status(fiber.StatusOK).SendString("Welcome, admin!")
|
||||
}
|
||||
|
@ -993,7 +993,7 @@ func (c *Ctx) Location(path string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
c.Location("http://example.com")
|
||||
|
||||
c.Location("/foo/bar")
|
||||
|
@ -1012,7 +1012,7 @@ func (c *Ctx) Method(override ...string) string
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
c.Method() // "POST"
|
||||
|
||||
c.Method("GET")
|
||||
|
@ -1031,7 +1031,7 @@ func (c *Ctx) MultipartForm() (*multipart.Form, error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Parse the multipart form:
|
||||
if form, err := c.MultipartForm(); err == nil {
|
||||
// => *multipart.Form
|
||||
|
@ -1070,17 +1070,17 @@ func (c *Ctx) Next() error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
fmt.Println("1st route!")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
app.Get("*", func(c *fiber.Ctx) error {
|
||||
app.Get("*", func(c fiber.Ctx) error {
|
||||
fmt.Println("2nd route!")
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
fmt.Println("3rd route!")
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
@ -1097,7 +1097,7 @@ func (c *Ctx) OriginalURL() string
|
|||
```go title="Example"
|
||||
// GET http://example.com/search?q=something
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.OriginalURL() // "/search?q=something"
|
||||
|
||||
// ...
|
||||
|
@ -1121,14 +1121,14 @@ func (c *Ctx) Params(key string, defaultValue ...string) string
|
|||
|
||||
```go title="Example"
|
||||
// GET http://example.com/user/fenny
|
||||
app.Get("/user/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:name", func(c fiber.Ctx) error {
|
||||
c.Params("name") // "fenny"
|
||||
|
||||
// ...
|
||||
})
|
||||
|
||||
// GET http://example.com/user/fenny/123
|
||||
app.Get("/user/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/*", func(c fiber.Ctx) error {
|
||||
c.Params("*") // "fenny/123"
|
||||
c.Params("*1") // "fenny/123"
|
||||
|
||||
|
@ -1148,7 +1148,7 @@ c.Params("*2") // "blue/xs"
|
|||
For reasons of **downward compatibility**, the first parameter segment for the parameter character can also be accessed without the counter.
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/v1/*/shop/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/v1/*/shop/*", func(c fiber.Ctx) error {
|
||||
c.Params("*") // outputs the values of the first wildcard segment
|
||||
})
|
||||
```
|
||||
|
@ -1173,7 +1173,7 @@ func (c *Ctx) ParamsInt(key string) (int, error)
|
|||
|
||||
```go title="Example"
|
||||
// GET http://example.com/user/123
|
||||
app.Get("/user/:id", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:id", func(c fiber.Ctx) error {
|
||||
id, err := c.ParamsInt("id") // int 123 and no error
|
||||
|
||||
// ...
|
||||
|
@ -1193,7 +1193,7 @@ func (c *Ctx) ParamsParser(out interface{}) error
|
|||
|
||||
```go title="Example"
|
||||
// GET http://example.com/user/111
|
||||
app.Get("/user/:id", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:id", func(c fiber.Ctx) error {
|
||||
param := struct {ID uint `params:"id"`}{}
|
||||
|
||||
c.ParamsParser(¶m) // "{"id": 111}"
|
||||
|
@ -1214,7 +1214,7 @@ func (c *Ctx) Path(override ...string) string
|
|||
```go title="Example"
|
||||
// GET http://example.com/users?sort=desc
|
||||
|
||||
app.Get("/users", func(c *fiber.Ctx) error {
|
||||
app.Get("/users", func(c fiber.Ctx) error {
|
||||
c.Path() // "/users"
|
||||
|
||||
c.Path("/john")
|
||||
|
@ -1235,7 +1235,7 @@ func (c *Ctx) Protocol() string
|
|||
```go title="Example"
|
||||
// GET http://example.com
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Protocol() // "http"
|
||||
|
||||
// ...
|
||||
|
@ -1253,7 +1253,7 @@ func (c *Ctx) Queries() map[string]string
|
|||
```go title="Example"
|
||||
// GET http://example.com/?name=alex&want_pizza=false&id=
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
m := c.Queries()
|
||||
m["name"] // "alex"
|
||||
m["want_pizza"] // "false"
|
||||
|
@ -1265,7 +1265,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go title="Example"
|
||||
// GET http://example.com/?field1=value1&field1=value2&field2=value3
|
||||
|
||||
app.Get("/", func (c *fiber.Ctx) error {
|
||||
app.Get("/", func (c fiber.Ctx) error {
|
||||
m := c.Queries()
|
||||
m["field1"] // "value2"
|
||||
m["field2"] // value3
|
||||
|
@ -1275,7 +1275,7 @@ app.Get("/", func (c *fiber.Ctx) error {
|
|||
```go title="Example"
|
||||
// GET http://example.com/?list_a=1&list_a=2&list_a=3&list_b[]=1&list_b[]=2&list_b[]=3&list_c=1,2,3
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
m := c.Queries()
|
||||
m["list_a"] // "3"
|
||||
m["list_b[]"] // "3"
|
||||
|
@ -1286,7 +1286,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go title="Example"
|
||||
// GET /api/posts?filters.author.name=John&filters.category.name=Technology
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
m := c.Queries()
|
||||
m["filters.author.name"] // John
|
||||
m["filters.category.name"] // Technology
|
||||
|
@ -1296,7 +1296,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go title="Example"
|
||||
// GET /api/posts?tags=apple,orange,banana&filters[tags]=apple,orange,banana&filters[category][name]=fruits&filters.tags=apple,orange,banana&filters.category.name=fruits
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
m := c.Queries()
|
||||
m["tags"] // apple,orange,banana
|
||||
m["filters[tags]"] // apple,orange,banana
|
||||
|
@ -1321,7 +1321,7 @@ func (c *Ctx) Query(key string, defaultValue ...string) string
|
|||
```go title="Example"
|
||||
// GET http://example.com/?order=desc&brand=nike
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Query("order") // "desc"
|
||||
c.Query("brand") // "nike"
|
||||
c.Query("empty", "nike") // "nike"
|
||||
|
@ -1349,7 +1349,7 @@ func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool
|
|||
```go title="Example"
|
||||
// GET http://example.com/?name=alex&want_pizza=false&id=
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.QueryBool("want_pizza") // false
|
||||
c.QueryBool("want_pizza", true) // false
|
||||
c.QueryBool("name") // false
|
||||
|
@ -1381,7 +1381,7 @@ func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64
|
|||
```go title="Example"
|
||||
// GET http://example.com/?name=alex&amount=32.23&id=
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.QueryFloat("amount") // 32.23
|
||||
c.QueryFloat("amount", 3) // 32.23
|
||||
c.QueryFloat("name", 1) // 1
|
||||
|
@ -1412,7 +1412,7 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int
|
|||
```go title="Example"
|
||||
// GET http://example.com/?name=alex&wanna_cake=2&id=
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.QueryInt("wanna_cake", 1) // 2
|
||||
c.QueryInt("name", 1) // 1
|
||||
c.QueryInt("id", 1) // 1
|
||||
|
@ -1439,7 +1439,7 @@ type Person struct {
|
|||
Products []string `query:"products"`
|
||||
}
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
p := new(Person)
|
||||
|
||||
if err := c.QueryParser(p); err != nil {
|
||||
|
@ -1467,7 +1467,7 @@ func (c *Ctx) Range(size int) (Range, error)
|
|||
|
||||
```go title="Example"
|
||||
// Range: bytes=500-700, 700-900
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
b := c.Range(1000)
|
||||
if b.Type == "bytes" {
|
||||
for r := range r.Ranges {
|
||||
|
@ -1491,17 +1491,17 @@ func (c *Ctx) Redirect(location string, status ...int) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/coffee", func(c *fiber.Ctx) error {
|
||||
app.Get("/coffee", func(c fiber.Ctx) error {
|
||||
return c.Redirect("/teapot")
|
||||
})
|
||||
|
||||
app.Get("/teapot", func(c *fiber.Ctx) error {
|
||||
app.Get("/teapot", func(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusTeapot).Send("🍵 short and stout 🍵")
|
||||
})
|
||||
```
|
||||
|
||||
```go title="More examples"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Redirect("/foo/bar")
|
||||
return c.Redirect("../login")
|
||||
return c.Redirect("http://example.com")
|
||||
|
@ -1526,14 +1526,14 @@ func (c *Ctx) RedirectToRoute(routeName string, params fiber.Map, status ...int)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// /user/fiber
|
||||
return c.RedirectToRoute("user", fiber.Map{
|
||||
"name": "fiber"
|
||||
})
|
||||
})
|
||||
|
||||
app.Get("/with-queries", func(c *fiber.Ctx) error {
|
||||
app.Get("/with-queries", func(c fiber.Ctx) error {
|
||||
// /user/fiber?data[0][name]=john&data[0][age]=10&test=doe
|
||||
return c.RedirectToRoute("user", fiber.Map{
|
||||
"name": "fiber",
|
||||
|
@ -1541,7 +1541,7 @@ app.Get("/with-queries", func(c *fiber.Ctx) error {
|
|||
})
|
||||
})
|
||||
|
||||
app.Get("/user/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:name", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("name"))
|
||||
}).Name("user")
|
||||
```
|
||||
|
@ -1559,15 +1559,15 @@ func (c *Ctx) RedirectBack(fallback string, status ...int) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Home page")
|
||||
})
|
||||
app.Get("/test", func(c *fiber.Ctx) error {
|
||||
app.Get("/test", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/html")
|
||||
return c.SendString(`<a href="/back">Back</a>`)
|
||||
})
|
||||
|
||||
app.Get("/back", func(c *fiber.Ctx) error {
|
||||
app.Get("/back", func(c fiber.Ctx) error {
|
||||
return c.RedirectBack("/")
|
||||
})
|
||||
```
|
||||
|
@ -1589,7 +1589,7 @@ func (c *Ctx) Request() *fasthttp.Request
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Request().Header.Method()
|
||||
// => []byte("GET")
|
||||
})
|
||||
|
@ -1612,7 +1612,7 @@ type Person struct {
|
|||
Products []string `reqHeader:"products"`
|
||||
}
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
p := new(Person)
|
||||
|
||||
if err := c.ReqHeaderParser(p); err != nil {
|
||||
|
@ -1639,7 +1639,7 @@ func (c *Ctx) Response() *fasthttp.Response
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Response().BodyWriter().Write([]byte("Hello, World!"))
|
||||
// => "Hello, World!"
|
||||
return nil
|
||||
|
@ -1655,11 +1655,11 @@ func (c *Ctx) RestartRouting() error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/new", func(c *fiber.Ctx) error {
|
||||
app.Get("/new", func(c fiber.Ctx) error {
|
||||
return c.SendString("From /new")
|
||||
})
|
||||
|
||||
app.Get("/old", func(c *fiber.Ctx) error {
|
||||
app.Get("/old", func(c fiber.Ctx) error {
|
||||
c.Path("/new")
|
||||
return c.RestartRouting()
|
||||
})
|
||||
|
@ -1677,7 +1677,7 @@ func (c *Ctx) Route() *Route
|
|||
// http://localhost:8080/hello
|
||||
|
||||
|
||||
app.Get("/hello/:name", func(c *fiber.Ctx) error {
|
||||
app.Get("/hello/:name", func(c fiber.Ctx) error {
|
||||
r := c.Route()
|
||||
fmt.Println(r.Method, r.Path, r.Params, r.Handlers)
|
||||
// GET /hello/:name handler [name]
|
||||
|
@ -1692,7 +1692,7 @@ Do not rely on `c.Route()` in middlewares **before** calling `c.Next()` - `c.Rou
|
|||
|
||||
```go title="Example"
|
||||
func MyMiddleware() fiber.Handler {
|
||||
return func(c *fiber.Ctx) error {
|
||||
return func(c fiber.Ctx) error {
|
||||
beforeNext := c.Route().Path // Will be '/'
|
||||
err := c.Next()
|
||||
afterNext := c.Route().Path // Will be '/hello/:name'
|
||||
|
@ -1710,7 +1710,7 @@ func (c *Ctx) SaveFile(fh *multipart.FileHeader, path string) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Parse the multipart form:
|
||||
if form, err := c.MultipartForm(); err == nil {
|
||||
// => *multipart.Form
|
||||
|
@ -1745,7 +1745,7 @@ func (c *Ctx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, s
|
|||
```go title="Example"
|
||||
storage := memory.New()
|
||||
|
||||
app.Post("/", func(c *fiber.Ctx) error {
|
||||
app.Post("/", func(c fiber.Ctx) error {
|
||||
// Parse the multipart form:
|
||||
if form, err := c.MultipartForm(); err == nil {
|
||||
// => *multipart.Form
|
||||
|
@ -1791,7 +1791,7 @@ func (c *Ctx) Send(body []byte) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Send([]byte("Hello, World!")) // => "Hello, World!"
|
||||
})
|
||||
```
|
||||
|
@ -1808,7 +1808,7 @@ func (c *Ctx) SendStream(stream io.Reader, size ...int) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
// => "Hello, World!"
|
||||
|
||||
|
@ -1830,7 +1830,7 @@ func (c *Ctx) SendFile(file string, compress ...bool) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/not-found", func(c *fiber.Ctx) error {
|
||||
app.Get("/not-found", func(c fiber.Ctx) error {
|
||||
return c.SendFile("./public/404.html");
|
||||
|
||||
// Disable compression
|
||||
|
@ -1843,7 +1843,7 @@ If the file contains an url specific character you have to escape it before pass
|
|||
:::
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/file-with-url-chars", func(c *fiber.Ctx) error {
|
||||
app.Get("/file-with-url-chars", func(c fiber.Ctx) error {
|
||||
return c.SendFile(url.PathEscape("hash_sign_#.txt"))
|
||||
})
|
||||
```
|
||||
|
@ -1865,7 +1865,7 @@ func (c *Ctx) SendStatus(status int) error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/not-found", func(c *fiber.Ctx) error {
|
||||
app.Get("/not-found", func(c fiber.Ctx) error {
|
||||
return c.SendStatus(415)
|
||||
// => 415 "Unsupported Media Type"
|
||||
|
||||
|
@ -1884,7 +1884,7 @@ func (c *Ctx) Set(key string, val string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Set("Content-Type", "text/plain")
|
||||
// => "Content-type: text/plain"
|
||||
|
||||
|
@ -1946,14 +1946,14 @@ type Demo struct {
|
|||
Body string `form:"body" query:"body"`
|
||||
}
|
||||
|
||||
app.Post("/body", func(c *fiber.Ctx) error {
|
||||
app.Post("/body", func(c fiber.Ctx) error {
|
||||
var d Demo
|
||||
c.BodyParser(&d)
|
||||
fmt.Println("d.Date", d.Date.String())
|
||||
return c.JSON(d)
|
||||
})
|
||||
|
||||
app.Get("/query", func(c *fiber.Ctx) error {
|
||||
app.Get("/query", func(c fiber.Ctx) error {
|
||||
var d Demo
|
||||
c.QueryParser(&d)
|
||||
fmt.Println("d.Date", d.Date.String())
|
||||
|
@ -1975,7 +1975,7 @@ func (c *Ctx) SetUserContext(ctx context.Context)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
ctx := context.Background()
|
||||
c.SetUserContext(ctx)
|
||||
// Here ctx could be any context implementation
|
||||
|
@ -2005,16 +2005,16 @@ func (c *Ctx) Status(status int) *Ctx
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/fiber", func(c *fiber.Ctx) error {
|
||||
app.Get("/fiber", func(c fiber.Ctx) error {
|
||||
c.Status(fiber.StatusOK)
|
||||
return nil
|
||||
}
|
||||
|
||||
app.Get("/hello", func(c *fiber.Ctx) error {
|
||||
app.Get("/hello", func(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusBadRequest).SendString("Bad Request")
|
||||
}
|
||||
|
||||
app.Get("/world", func(c *fiber.Ctx) error {
|
||||
app.Get("/world", func(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusNotFound).SendFile("./public/gopher.png")
|
||||
})
|
||||
```
|
||||
|
@ -2032,7 +2032,7 @@ func (c *Ctx) Subdomains(offset ...int) []string
|
|||
```go title="Example"
|
||||
// Host: "tobi.ferrets.example.com"
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Subdomains() // ["ferrets", "tobi"]
|
||||
c.Subdomains(1) // ["tobi"]
|
||||
|
||||
|
@ -2049,7 +2049,7 @@ func (c *Ctx) Type(ext string, charset ...string) *Ctx
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Type(".html") // => "text/html"
|
||||
c.Type("html") // => "text/html"
|
||||
c.Type("png") // => "image/png"
|
||||
|
@ -2070,7 +2070,7 @@ func (c *Ctx) UserContext() context.Context
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
ctx := c.UserContext()
|
||||
// ctx is context implementation set by user
|
||||
|
||||
|
@ -2091,7 +2091,7 @@ func (c *Ctx) Vary(fields ...string)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Vary("Origin") // => Vary: Origin
|
||||
c.Vary("User-Agent") // => Vary: Origin, User-Agent
|
||||
|
||||
|
@ -2114,7 +2114,7 @@ func (c *Ctx) Write(p []byte) (n int, err error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Write([]byte("Hello, World!")) // => "Hello, World!"
|
||||
|
||||
fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
|
||||
|
@ -2130,7 +2130,7 @@ func (c *Ctx) Writef(f string, a ...interface{}) (n int, err error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
world := "World!"
|
||||
c.Writef("Hello, %s", world) // => "Hello, World!"
|
||||
|
||||
|
@ -2147,7 +2147,7 @@ func (c *Ctx) WriteString(s string) (n int, err error)
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.WriteString("Hello, World!") // => "Hello, World!"
|
||||
|
||||
fmt.Fprintf(c, "%s\n", "Hello, World!") // "Hello, World!Hello, World!"
|
||||
|
@ -2165,7 +2165,7 @@ func (c *Ctx) XHR() bool
|
|||
```go title="Example"
|
||||
// X-Requested-With: XMLHttpRequest
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.XHR() // true
|
||||
|
||||
// ...
|
||||
|
@ -2191,7 +2191,7 @@ type SomeStruct struct {
|
|||
Age uint8 `xml:"Age"`
|
||||
}
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Create data struct:
|
||||
data := SomeStruct{
|
||||
Name: "Grame",
|
||||
|
|
|
@ -91,7 +91,7 @@ func NewError(code int, message ...string) *Error
|
|||
```
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return fiber.NewError(782, "Custom error message")
|
||||
})
|
||||
```
|
||||
|
|
|
@ -15,7 +15,7 @@ Converter for net/http handlers to/from Fiber request handlers, special thanks t
|
|||
| FiberHandler | `FiberHandler(h fiber.Handler) http.Handler` | fiber.Handler -> http.Handler
|
||||
| FiberHandlerFunc | `FiberHandlerFunc(h fiber.Handler) http.HandlerFunc` | fiber.Handler -> http.HandlerFunc
|
||||
| FiberApp | `FiberApp(app *fiber.App) http.HandlerFunc` | Fiber app -> http.HandlerFunc
|
||||
| ConvertRequest | `ConvertRequest(c *fiber.Ctx, forServer bool) (*http.Request, error)` | fiber.Ctx -> http.Request
|
||||
| ConvertRequest | `ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error)` | fiber.Ctx -> http.Request
|
||||
| CopyContextToFiberContext | `CopyContextToFiberContext(context interface{}, requestContext *fasthttp.RequestCtx)` | context.Context -> fasthttp.RequestCtx
|
||||
|
||||
## Examples
|
||||
|
@ -108,7 +108,7 @@ func main() {
|
|||
http.ListenAndServe(":3000", nil)
|
||||
}
|
||||
|
||||
func greet(c *fiber.Ctx) error {
|
||||
func greet(c fiber.Ctx) error {
|
||||
return c.SendString("Hello World!")
|
||||
}
|
||||
```
|
||||
|
@ -133,7 +133,7 @@ func main() {
|
|||
http.ListenAndServe(":3000", adaptor.FiberApp(app))
|
||||
}
|
||||
|
||||
func greet(c *fiber.Ctx) error {
|
||||
func greet(c fiber.Ctx) error {
|
||||
return c.SendString("Hello World!")
|
||||
}
|
||||
```
|
||||
|
@ -158,7 +158,7 @@ func main() {
|
|||
http.ListenAndServe(":3000", adaptor.FiberApp(app))
|
||||
}
|
||||
|
||||
func greetWithHTTPReq(c *fiber.Ctx) error {
|
||||
func greetWithHTTPReq(c fiber.Ctx) error {
|
||||
httpReq, err := adaptor.ConvertRequest(c, false)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
|
@ -10,8 +10,8 @@ Basic Authentication middleware for [Fiber](https://github.com/gofiber/fiber) th
|
|||
|
||||
```go
|
||||
func New(config Config) fiber.Handler
|
||||
func UsernameFromContext(c *fiber.Ctx) string
|
||||
func PasswordFromContext(c *fiber.Ctx) string
|
||||
func UsernameFromContext(c fiber.Ctx) string
|
||||
func PasswordFromContext(c fiber.Ctx) string
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
@ -52,7 +52,7 @@ app.Use(basicauth.New(basicauth.Config{
|
|||
}
|
||||
return false
|
||||
},
|
||||
Unauthorized: func(c *fiber.Ctx) error {
|
||||
Unauthorized: func(c fiber.Ctx) error {
|
||||
return c.SendFile("./unauthorized.html")
|
||||
},
|
||||
}))
|
||||
|
@ -61,7 +61,7 @@ app.Use(basicauth.New(basicauth.Config{
|
|||
Getting the username and password
|
||||
|
||||
```go
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
username := basicauth.UsernameFromContext(c)
|
||||
password := basicauth.PasswordFromContext(c)
|
||||
log.Printf("Username: %s Password: %s", username, password)
|
||||
|
@ -73,7 +73,7 @@ func handler(c *fiber.Ctx) error {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:----------------|:----------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Users | `map[string]string` | Users defines the allowed credentials. | `map[string]string{}` |
|
||||
| Realm | `string` | Realm is a string to define the realm attribute of BasicAuth. The realm identifies the system to authenticate against and can be used by clients to save credentials. | `"Restricted"` |
|
||||
| Authorizer | `func(string, string) bool` | Authorizer defines a function to check the credentials. It will be called with a username and password and is expected to return true or false to indicate approval. | `nil` |
|
||||
|
|
|
@ -35,7 +35,7 @@ app.Use(cache.New())
|
|||
|
||||
// Or extend your config for customization
|
||||
app.Use(cache.New(cache.Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
Next: func(c fiber.Ctx) bool {
|
||||
return c.Query("noCache") == "true"
|
||||
},
|
||||
Expiration: 30 * time.Minute,
|
||||
|
@ -47,16 +47,16 @@ Or you can custom key and expire time like this:
|
|||
|
||||
```go
|
||||
app.Use(cache.New(cache.Config{
|
||||
ExpirationGenerator: func(c *fiber.Ctx, cfg *cache.Config) time.Duration {
|
||||
ExpirationGenerator: func(c fiber.Ctx, cfg *cache.Config) time.Duration {
|
||||
newCacheTime, _ := strconv.Atoi(c.GetRespHeader("Cache-Time", "600"))
|
||||
return time.Second * time.Duration(newCacheTime)
|
||||
},
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
KeyGenerator: func(c fiber.Ctx) string {
|
||||
return utils.CopyString(c.Path())
|
||||
},
|
||||
}))
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
c.Response().Header.Add("Cache-Time", "6000")
|
||||
return c.SendString("hi")
|
||||
})
|
||||
|
@ -66,15 +66,15 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------------------|:------------------------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function that is executed before creating the cache entry and can be used to execute the request without cache creation. If an entry already exists, it will be used. If you want to completely bypass the cache functionality in certain cases, you should use the [skip middleware](./skip.md). | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function that is executed before creating the cache entry and can be used to execute the request without cache creation. If an entry already exists, it will be used. If you want to completely bypass the cache functionality in certain cases, you should use the [skip middleware](./skip.md). | `nil` |
|
||||
| Expiration | `time.Duration` | Expiration is the time that a cached response will live. | `1 * time.Minute` |
|
||||
| CacheHeader | `string` | CacheHeader is the header on the response header that indicates the cache status, with the possible return values "hit," "miss," or "unreachable." | `X-Cache` |
|
||||
| CacheControl | `bool` | CacheControl enables client-side caching if set to true. | `false` |
|
||||
| KeyGenerator | `func(*fiber.Ctx) string` | Key allows you to generate custom keys. | `func(c *fiber.Ctx) string { return utils.CopyString(c.Path()) }` |
|
||||
| ExpirationGenerator | `func(*fiber.Ctx, *cache.Config) time.Duration` | ExpirationGenerator allows you to generate custom expiration keys based on the request. | `nil` |
|
||||
| KeyGenerator | `func(fiber.Ctx) string` | Key allows you to generate custom keys. | `func(c fiber.Ctx) string { return utils.CopyString(c.Path()) }` |
|
||||
| ExpirationGenerator | `func(fiber.Ctx, *cache.Config) time.Duration` | ExpirationGenerator allows you to generate custom expiration keys based on the request. | `nil` |
|
||||
| Storage | `fiber.Storage` | Store is used to store the state of the middleware. | In-memory store |
|
||||
| Store (Deprecated) | `fiber.Storage` | Deprecated: Use Storage instead. | In-memory store |
|
||||
| Key (Deprecated) | `func(*fiber.Ctx) string` | Deprecated: Use KeyGenerator instead. | `nil` |
|
||||
| Key (Deprecated) | `func(fiber.Ctx) string` | Deprecated: Use KeyGenerator instead. | `nil` |
|
||||
| StoreResponseHeaders | `bool` | StoreResponseHeaders allows you to store additional headers generated by next middlewares & handler. | `false` |
|
||||
| MaxBytes | `uint` | MaxBytes is the maximum number of bytes of response bodies simultaneously stored in cache. | `0` (No limit) |
|
||||
| Methods | `[]string` | Methods specifies the HTTP methods to cache. | `[]string{fiber.MethodGet, fiber.MethodHead}` |
|
||||
|
@ -87,7 +87,7 @@ var ConfigDefault = Config{
|
|||
Expiration: 1 * time.Minute,
|
||||
CacheHeader: "X-Cache",
|
||||
CacheControl: false,
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
KeyGenerator: func(c fiber.Ctx) string {
|
||||
return utils.CopyString(c.Path())
|
||||
},
|
||||
ExpirationGenerator: nil,
|
||||
|
|
|
@ -40,7 +40,7 @@ app.Use(compress.New(compress.Config{
|
|||
|
||||
// Skip middleware for specific routes
|
||||
app.Use(compress.New(compress.Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
Next: func(c fiber.Ctx) bool {
|
||||
return c.Path() == "/dont_compress"
|
||||
},
|
||||
Level: compress.LevelBestSpeed, // 1
|
||||
|
@ -53,7 +53,7 @@ app.Use(compress.New(compress.Config{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------|:------------------------|:--------------------------------------------------------------------|:-------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Level | `Level` | Level determines the compression algorithm. | `LevelDefault (0)` |
|
||||
|
||||
Possible values for the "Level" field are:
|
||||
|
|
|
@ -60,7 +60,7 @@ app.Use(cors.New(cors.Config{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-----------------|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| AllowOriginsFunc | `func(origin string) bool` | AllowOriginsFunc defines a function that will set the 'access-control-allow-origin' response header to the 'origin' request header when returned true. | `nil` |
|
||||
| AllowOrigins | `string` | AllowOrigin defines a comma separated list of origins that may access the resource. | `"*"` |
|
||||
| AllowMethods | `string` | AllowMethods defines a list of methods allowed when accessing the resource. This is used in response to a preflight request. | `"GET,POST,HEAD,PUT,DELETE,PATCH"` |
|
||||
|
|
|
@ -102,10 +102,10 @@ It's important to note that the token is sent as a header on every request. If y
|
|||
|
||||
```go
|
||||
func New(config ...Config) fiber.Handler
|
||||
func TokenFromContext(c *fiber.Ctx) string
|
||||
func HandlerFromContext(c *fiber.Ctx) *Handler
|
||||
func TokenFromContext(c fiber.Ctx) string
|
||||
func HandlerFromContext(c fiber.Ctx) *Handler
|
||||
|
||||
func (h *Handler) DeleteToken(c *fiber.Ctx) error
|
||||
func (h *Handler) DeleteToken(c fiber.Ctx) error
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
@ -132,7 +132,7 @@ app.Use(csrf.New(csrf.Config{
|
|||
CookieSameSite: "Lax",
|
||||
Expiration: 1 * time.Hour,
|
||||
KeyGenerator: utils.UUIDv4,
|
||||
Extractor: func(c *fiber.Ctx) (string, error) { ... },
|
||||
Extractor: func(c fiber.Ctx) (string, error) { ... },
|
||||
}))
|
||||
```
|
||||
|
||||
|
@ -145,7 +145,7 @@ Getting the CSRF token in a handler:
|
|||
```go
|
||||
|
||||
```go
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
handler := csrf.HandlerFromContext(c)
|
||||
token := csrf.TokenFromContext(c)
|
||||
if handler == nil {
|
||||
|
@ -174,7 +174,7 @@ func handler(c *fiber.Ctx) error {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:------------------|:-----------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| KeyLookup | `string` | KeyLookup is a string in the form of "`<source>:<key>`" that is used to create an Extractor that extracts the token from the request. Possible values: "`header:<name>`", "`query:<name>`", "`param:<name>`", "`form:<name>`", "`cookie:<name>`". Ignored if an Extractor is explicitly set. | "header:X-CSRF-Token" |
|
||||
| CookieName | `string` | Name of the csrf cookie. This cookie will store the csrf key. | "csrf_" |
|
||||
| CookieDomain | `string` | Domain of the CSRF cookie. | "" |
|
||||
|
@ -190,7 +190,7 @@ func handler(c *fiber.Ctx) error {
|
|||
| SessionKey | `string` | SessionKey is the key used to store the token in the session. | "csrfToken" |
|
||||
| KeyGenerator | `func() string` | KeyGenerator creates a new CSRF token. | utils.UUID |
|
||||
| ErrorHandler | `fiber.ErrorHandler` | ErrorHandler is executed when an error is returned from fiber.Handler. | DefaultErrorHandler |
|
||||
| Extractor | `func(*fiber.Ctx) (string, error)` | Extractor returns the CSRF token. If set, this will be used in place of an Extractor based on KeyLookup. | Extractor based on KeyLookup |
|
||||
| Extractor | `func(fiber.Ctx) (string, error)` | Extractor returns the CSRF token. If set, this will be used in place of an Extractor based on KeyLookup. | Extractor based on KeyLookup |
|
||||
|
||||
### Default Config
|
||||
|
||||
|
@ -256,7 +256,7 @@ Example, returning a JSON response for API requests and rendering an error page
|
|||
|
||||
```go
|
||||
app.Use(csrf.New(csrf.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
ErrorHandler: func(c fiber.Ctx, err error) error {
|
||||
accepts := c.Accepts("html", "json")
|
||||
path := c.Path()
|
||||
if accepts == "json" || strings.HasPrefix(path, "/api/") {
|
||||
|
|
|
@ -84,16 +84,16 @@ var ConfigDefault = Config{
|
|||
=======
|
||||
| Property | Type | Description | Default |
|
||||
|:---------------|:------------------------|:-------------------------------------------------------------------------------------|:-------------------------------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| IsEarlyData | `func(*fiber.Ctx) bool` | IsEarlyData returns whether the request is an early-data request. | Function checking if "Early-Data" header equals "1" |
|
||||
| AllowEarlyData | `func(*fiber.Ctx) bool` | AllowEarlyData returns whether the early-data request should be allowed or rejected. | Function rejecting on unsafe and allowing safe methods |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| IsEarlyData | `func(fiber.Ctx) bool` | IsEarlyData returns whether the request is an early-data request. | Function checking if "Early-Data" header equals "1" |
|
||||
| AllowEarlyData | `func(fiber.Ctx) bool` | AllowEarlyData returns whether the early-data request should be allowed or rejected. | Function rejecting on unsafe and allowing safe methods |
|
||||
| Error | `error` | Error is returned in case an early-data request is rejected. | `fiber.ErrTooEarly` |
|
||||
|
||||
## Default Config
|
||||
|
||||
```go
|
||||
var ConfigDefault = Config{
|
||||
IsEarlyData: func(c *fiber.Ctx) bool {
|
||||
IsEarlyData: func(c fiber.Ctx) bool {
|
||||
return c.Get(DefaultHeaderName) == DefaultHeaderTrueValue
|
||||
>>>>>>> origin/master:docs/api/middleware/earlydata.md
|
||||
},
|
||||
|
|
|
@ -88,7 +88,7 @@ type Config struct {
|
|||
=======
|
||||
| Property | Type | Description | Default |
|
||||
|:----------|:----------------------------------------------------|:----------------------------------------------------------------------------------------------------|:-----------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Except | `[]string` | Array of cookie keys that should not be encrypted. | `[]` |
|
||||
| Key | `string` | Base64 encoded unique key to encode & decode cookies. Required. Key length should be 32 characters. | (No default, required field) |
|
||||
| Encryptor | `func(decryptedString, key string) (string, error)` | Custom function to encrypt cookies. | `EncryptCookie` |
|
||||
|
|
|
@ -30,7 +30,7 @@ After you initiate your Fiber app, you can use the following possibilities:
|
|||
app.Use(etag.New())
|
||||
|
||||
// Get / receives Etag: "13-1831710635" in response header
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
||||
|
@ -40,7 +40,7 @@ app.Use(etag.New(etag.Config{
|
|||
}))
|
||||
|
||||
// Get / receives Etag: "W/"13-1831710635" in response header
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
@ -50,7 +50,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
| Property | Type | Description | Default |
|
||||
|:---------|:------------------------|:-------------------------------------------------------------------------------------------------------------------|:--------|
|
||||
| Weak | `bool` | Weak indicates that a weak validator is used. Weak etags are easy to generate but are less useful for comparisons. | `false` |
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
|
||||
## Default Config
|
||||
|
||||
|
|
|
@ -28,7 +28,7 @@ After you initiate your Fiber app, you can use the following possibilities:
|
|||
var count = expvar.NewInt("count")
|
||||
|
||||
app.Use(expvarmw.New())
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
count.Add(1)
|
||||
|
||||
return c.SendString(fmt.Sprintf("hello expvar count %d", count.Value()))
|
||||
|
@ -61,7 +61,7 @@ curl 127.0.0.1:3000/debug/vars?r=c
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------|:------------------------|:--------------------------------------------------------------------|:--------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
|
||||
## Default Config
|
||||
|
||||
|
|
|
@ -44,7 +44,7 @@ app.Use(favicon.New(favicon.Config{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-------------|:------------------------|:---------------------------------------------------------------------------------|:---------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Data | `[]byte` | Raw data of the favicon file. This can be used instead of `File`. | `nil` |
|
||||
| File | `string` | File holds the path to an actual favicon that will be cached. | "" |
|
||||
| URL | `string` | URL for favicon handler. | "/favicon.ico" |
|
||||
|
|
|
@ -231,7 +231,7 @@ func main() {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-------------------|:------------------------|:------------------------------------------------------------------------------------------------------------|:-------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Root | `http.FileSystem` | Root is a FileSystem that provides access to a collection of files and directories. | `nil` |
|
||||
| PathPrefix | `string` | PathPrefix defines a prefix to be added to a filepath when reading a file from the FileSystem. | "" |
|
||||
| Browse | `bool` | Enable directory browsing. | `false` |
|
||||
|
@ -261,7 +261,7 @@ var ConfigDefault = Config{
|
|||
Serves a file from an [HTTP file system](https://pkg.go.dev/net/http#FileSystem) at the specified path.
|
||||
|
||||
```go title="Signature" title="Signature"
|
||||
func SendFile(c *fiber.Ctx, filesystem http.FileSystem, path string) error
|
||||
func SendFile(c fiber.Ctx, filesystem http.FileSystem, path string) error
|
||||
```
|
||||
Import the middleware package that is part of the Fiber web framework
|
||||
|
||||
|
@ -274,7 +274,7 @@ import (
|
|||
|
||||
```go title="Example"
|
||||
// Define a route to serve a specific file
|
||||
app.Get("/download", func(c *fiber.Ctx) error {
|
||||
app.Get("/download", func(c fiber.Ctx) error {
|
||||
// Serve the file using SendFile function
|
||||
err := filesystem.SendFile(c, http.Dir("your/filesystem/root"), "path/to/your/file.txt")
|
||||
if err != nil {
|
||||
|
@ -294,7 +294,7 @@ app.Use("/", filesystem.New(filesystem.Config{
|
|||
}))
|
||||
|
||||
// For all other routes (wildcard "*"), serve the "index.html" file from the "build" directory.
|
||||
app.Use("*", func(ctx *fiber.Ctx) error {
|
||||
app.Use("*", func(ctx fiber.Ctx) error {
|
||||
return filesystem.SendFile(ctx, http.FS(f), "build/index.html")
|
||||
})
|
||||
```
|
||||
|
|
|
@ -26,7 +26,7 @@ func main() {
|
|||
|
||||
app.Use(helmet.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome!")
|
||||
})
|
||||
|
||||
|
@ -44,7 +44,7 @@ curl -I http://localhost:3000
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:--------------------------|:------------------------|:--------------------------------------------|:-----------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip middleware. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip middleware. | `nil` |
|
||||
| XSSProtection | `string` | XSSProtection | "0" |
|
||||
| ContentTypeNosniff | `string` | ContentTypeNosniff | "nosniff" |
|
||||
| XFrameOptions | `string` | XFrameOptions | "SAMEORIGIN" |
|
||||
|
|
|
@ -48,7 +48,7 @@ app.Use(idempotency.New(idempotency.Config{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:--------------------|:------------------------|:-----------------------------------------------------------------------------------------|:-------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | A function for safe methods |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | A function for safe methods |
|
||||
| Lifetime | `time.Duration` | Lifetime is the maximum lifetime of an idempotency key. | 30 * time.Minute |
|
||||
| KeyHeader | `string` | KeyHeader is the name of the header that contains the idempotency key. | "X-Idempotency-Key" |
|
||||
| KeyHeaderValidate | `func(string) error` | KeyHeaderValidate defines a function to validate the syntax of the idempotency header. | A function for UUID validation |
|
||||
|
@ -60,7 +60,7 @@ app.Use(idempotency.New(idempotency.Config{
|
|||
|
||||
```go
|
||||
var ConfigDefault = Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
Next: func(c fiber.Ctx) bool {
|
||||
// Skip middleware if the request was done using a safe HTTP method
|
||||
return fiber.IsMethodSafe(c.Method())
|
||||
},
|
||||
|
|
|
@ -29,7 +29,7 @@ var (
|
|||
apiKey = "correct horse battery staple"
|
||||
)
|
||||
|
||||
func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
|
||||
func validateAPIKey(c fiber.Ctx, key string) (bool, error) {
|
||||
hashedAPIKey := sha256.Sum256([]byte(apiKey))
|
||||
hashedKey := sha256.Sum256([]byte(key))
|
||||
|
||||
|
@ -48,7 +48,7 @@ func main() {
|
|||
Validator: validateAPIKey,
|
||||
}))
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Successfully authenticated!")
|
||||
})
|
||||
|
||||
|
@ -97,7 +97,7 @@ var (
|
|||
}
|
||||
)
|
||||
|
||||
func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
|
||||
func validateAPIKey(c fiber.Ctx, key string) (bool, error) {
|
||||
hashedAPIKey := sha256.Sum256([]byte(apiKey))
|
||||
hashedKey := sha256.Sum256([]byte(key))
|
||||
|
||||
|
@ -107,7 +107,7 @@ func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
|
|||
return false, keyauth.ErrMissingOrMalformedAPIKey
|
||||
}
|
||||
|
||||
func authFilter(c *fiber.Ctx) bool {
|
||||
func authFilter(c fiber.Ctx) bool {
|
||||
originalURL := strings.ToLower(c.OriginalURL())
|
||||
|
||||
for _, pattern := range protectedURLs {
|
||||
|
@ -127,13 +127,13 @@ func main() {
|
|||
Validator: validateAPIKey,
|
||||
}))
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome")
|
||||
})
|
||||
app.Get("/authenticated", func(c *fiber.Ctx) error {
|
||||
app.Get("/authenticated", func(c fiber.Ctx) error {
|
||||
return c.SendString("Successfully authenticated!")
|
||||
})
|
||||
app.Get("/auth2", func(c *fiber.Ctx) error {
|
||||
app.Get("/auth2", func(c fiber.Ctx) error {
|
||||
return c.SendString("Successfully authenticated 2!")
|
||||
})
|
||||
|
||||
|
@ -177,7 +177,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
|
||||
authMiddleware := keyauth.New(keyauth.Config{
|
||||
Validator: func(c *fiber.Ctx, key string) (bool, error) {
|
||||
Validator: func(c fiber.Ctx, key string) (bool, error) {
|
||||
hashedAPIKey := sha256.Sum256([]byte(apiKey))
|
||||
hashedKey := sha256.Sum256([]byte(key))
|
||||
|
||||
|
@ -188,11 +188,11 @@ func main() {
|
|||
},
|
||||
})
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Welcome")
|
||||
})
|
||||
|
||||
app.Get("/allowed", authMiddleware, func(c *fiber.Ctx) error {
|
||||
app.Get("/allowed", authMiddleware, func(c fiber.Ctx) error {
|
||||
return c.SendString("Successfully authenticated!")
|
||||
})
|
||||
|
||||
|
@ -216,21 +216,21 @@ curl --header "Authorization: Bearer my-super-secret-key" http://localhost:3000
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------------|:-----------------------------------------|:-------------------------------------------------------------------------------------------------------|:------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| SuccessHandler | `fiber.Handler` | SuccessHandler defines a function which is executed for a valid key. | `nil` |
|
||||
| ErrorHandler | `fiber.ErrorHandler` | ErrorHandler defines a function which is executed for an invalid key. | `401 Invalid or expired key` |
|
||||
| KeyLookup | `string` | KeyLookup is a string in the form of "`<source>:<name>`" that is used to extract key from the request. | "header:Authorization" |
|
||||
| AuthScheme | `string` | AuthScheme to be used in the Authorization header. | "Bearer" |
|
||||
| Validator | `func(*fiber.Ctx, string) (bool, error)` | Validator is a function to validate the key. | A function for key validation |
|
||||
| Validator | `func(fiber.Ctx, string) (bool, error)` | Validator is a function to validate the key. | A function for key validation |
|
||||
|
||||
## Default Config
|
||||
|
||||
```go
|
||||
var ConfigDefault = Config{
|
||||
SuccessHandler: func(c *fiber.Ctx) error {
|
||||
SuccessHandler: func(c fiber.Ctx) error {
|
||||
return c.Next()
|
||||
},
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
ErrorHandler: func(c fiber.Ctx, err error) error {
|
||||
if err == ErrMissingOrMalformedAPIKey {
|
||||
return c.Status(fiber.StatusUnauthorized).SendString(err.Error())
|
||||
}
|
||||
|
|
|
@ -39,15 +39,15 @@ app.Use(limiter.New())
|
|||
|
||||
// Or extend your config for customization
|
||||
app.Use(limiter.New(limiter.Config{
|
||||
Next: func(c *fiber.Ctx) bool {
|
||||
Next: func(c fiber.Ctx) bool {
|
||||
return c.IP() == "127.0.0.1"
|
||||
},
|
||||
Max: 20,
|
||||
Expiration: 30 * time.Second,
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
KeyGenerator: func(c fiber.Ctx) string {
|
||||
return c.Get("x-forwarded-for")
|
||||
},
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
LimitReached: func(c fiber.Ctx) error {
|
||||
return c.SendFile("./toofast.html")
|
||||
},
|
||||
Storage: myCustomStorage{},
|
||||
|
@ -78,9 +78,9 @@ rate = weightOfPreviousWindpw + current window's amount request.
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-----------------------|:--------------------------|:--------------------------------------------------------------------------------------------|:-----------------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Max | `int` | Max number of recent connections during `Expiration` seconds before sending a 429 response. | 5 |
|
||||
| KeyGenerator | `func(*fiber.Ctx) string` | KeyGenerator allows you to generate custom keys, by default c.IP() is used. | A function using c.IP() as the default |
|
||||
| KeyGenerator | `func(fiber.Ctx) string` | KeyGenerator allows you to generate custom keys, by default c.IP() is used. | A function using c.IP() as the default |
|
||||
| Expiration | `time.Duration` | Expiration is the time on how long to keep records of requests in memory. | 1 * time.Minute |
|
||||
| LimitReached | `fiber.Handler` | LimitReached is called when a request hits the limit. | A function sending 429 response |
|
||||
| SkipFailedRequests | `bool` | When set to true, requests with StatusCode >= 400 won't be counted. | false |
|
||||
|
@ -89,7 +89,7 @@ rate = weightOfPreviousWindpw + current window's amount request.
|
|||
| LimiterMiddleware | `LimiterHandler` | LimiterMiddleware is the struct that implements a limiter middleware. | A new Fixed Window Rate Limiter |
|
||||
| Duration (Deprecated) | `time.Duration` | Deprecated: Use Expiration instead | - |
|
||||
| Store (Deprecated) | `fiber.Storage` | Deprecated: Use Storage instead | - |
|
||||
| Key (Deprecated) | `func(*fiber.Ctx) string` | Deprecated: Use KeyGenerator instead | - |
|
||||
| Key (Deprecated) | `func(fiber.Ctx) string` | Deprecated: Use KeyGenerator instead | - |
|
||||
|
||||
:::note
|
||||
A custom store can be used if it implements the `Storage` interface - more details and an example can be found in `store.go`.
|
||||
|
@ -101,10 +101,10 @@ A custom store can be used if it implements the `Storage` interface - more detai
|
|||
var ConfigDefault = Config{
|
||||
Max: 5,
|
||||
Expiration: 1 * time.Minute,
|
||||
KeyGenerator: func(c *fiber.Ctx) string {
|
||||
KeyGenerator: func(c fiber.Ctx) string {
|
||||
return c.IP()
|
||||
},
|
||||
LimitReached: func(c *fiber.Ctx) error {
|
||||
LimitReached: func(c fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusTooManyRequests)
|
||||
},
|
||||
SkipFailedRequests: false,
|
||||
|
|
|
@ -65,7 +65,7 @@ app.Use(logger.New(logger.Config{
|
|||
// Add Custom Tags
|
||||
app.Use(logger.New(logger.Config{
|
||||
CustomTags: map[string]logger.LogFunc{
|
||||
"custom_tag": func(output logger.Buffer, c *fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
|
||||
"custom_tag": func(output logger.Buffer, c fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
|
||||
return output.WriteString("it is a custom tag")
|
||||
},
|
||||
},
|
||||
|
@ -75,7 +75,7 @@ app.Use(logger.New(logger.Config{
|
|||
app.Use(logger.New(logger.Config{
|
||||
TimeFormat: time.RFC3339Nano,
|
||||
TimeZone: "Asia/Shanghai",
|
||||
Done: func(c *fiber.Ctx, logString []byte) {
|
||||
Done: func(c fiber.Ctx, logString []byte) {
|
||||
if c.Response().StatusCode() != fiber.StatusOK {
|
||||
reporter.SendToSlack(logString)
|
||||
}
|
||||
|
@ -94,8 +94,8 @@ app.Use(logger.New(logger.Config{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Done | `func(*fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Done | `func(fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` |
|
||||
| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` |
|
||||
| Format | `string` | Format defines the logging tags. | `[${time}] ${status} - ${latency} ${method} ${path}\n` |
|
||||
| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` |
|
||||
|
|
|
@ -54,7 +54,7 @@ You can also access the API endpoint with
|
|||
| Title | `string` | Metrics page title | "Fiber Monitor" |
|
||||
| Refresh | `time.Duration` | Refresh period | 3 seconds |
|
||||
| APIOnly | `bool` | Whether the service should expose only the monitoring API | false |
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| CustomHead | `string` | Custom HTML Code to Head Section(Before End) | empty |
|
||||
| FontURL | `string` | FontURL for specify font resource path or URL | "https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap" |
|
||||
| ChartJsURL | `string` | ChartJsURL for specify ChartJS library path or URL | "https://cdn.jsdelivr.net/npm/chart.js@2.9/dist/Chart.bundle.min.js" |
|
||||
|
|
|
@ -41,7 +41,7 @@ app.Use(pprof.New(pprof.Config{Prefix: "/endpoint-prefix"}))
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------|:------------------------|:------------------------------------------------------------------------------------------------------------------------------------------------|:--------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Prefix | `string` | Prefix defines a URL prefix added before "/debug/pprof". Note that it should start with (but not end with) a slash. Example: "/federated-fiber" | "" |
|
||||
|
||||
## Default Config
|
||||
|
|
|
@ -14,13 +14,13 @@ func Balancer(config Config) fiber.Handler
|
|||
// Forward performs the given http request and fills the given http response.
|
||||
func Forward(addr string, clients ...*fasthttp.Client) fiber.Handler
|
||||
// Do performs the given http request and fills the given http response.
|
||||
func Do(c *fiber.Ctx, addr string, clients ...*fasthttp.Client) error
|
||||
func Do(c fiber.Ctx, addr string, clients ...*fasthttp.Client) error
|
||||
// DoRedirects performs the given http request and fills the given http response while following up to maxRedirectsCount redirects.
|
||||
func DoRedirects(c *fiber.Ctx, addr string, maxRedirectsCount int, clients ...*fasthttp.Client) error
|
||||
func DoRedirects(c fiber.Ctx, addr string, maxRedirectsCount int, clients ...*fasthttp.Client) error
|
||||
// DoDeadline performs the given request and waits for response until the given deadline.
|
||||
func DoDeadline(c *fiber.Ctx, addr string, deadline time.Time, clients ...*fasthttp.Client) error
|
||||
func DoDeadline(c fiber.Ctx, addr string, deadline time.Time, clients ...*fasthttp.Client) error
|
||||
// DoTimeout performs the given request and waits for response during the given timeout duration.
|
||||
func DoTimeout(c *fiber.Ctx, addr string, timeout time.Duration, clients ...*fasthttp.Client) error
|
||||
func DoTimeout(c fiber.Ctx, addr string, timeout time.Duration, clients ...*fasthttp.Client) error
|
||||
// DomainForward the given http request based on the given domain and fills the given http response
|
||||
func DomainForward(hostname string, addr string, clients ...*fasthttp.Client) fiber.Handler
|
||||
// BalancerForward performs the given http request based round robin balancer and fills the given http response
|
||||
|
@ -65,7 +65,7 @@ app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif", &fasthttp.Clien
|
|||
}))
|
||||
|
||||
// Make request within handler
|
||||
app.Get("/:id", func(c *fiber.Ctx) error {
|
||||
app.Get("/:id", func(c fiber.Ctx) error {
|
||||
url := "https://i.imgur.com/"+c.Params("id")+".gif"
|
||||
if err := proxy.Do(c, url); err != nil {
|
||||
return err
|
||||
|
@ -76,7 +76,7 @@ app.Get("/:id", func(c *fiber.Ctx) error {
|
|||
})
|
||||
|
||||
// Make proxy requests while following redirects
|
||||
app.Get("/proxy", func(c *fiber.Ctx) error {
|
||||
app.Get("/proxy", func(c fiber.Ctx) error {
|
||||
if err := proxy.DoRedirects(c, "http://google.com", 3); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -86,7 +86,7 @@ app.Get("/proxy", func(c *fiber.Ctx) error {
|
|||
})
|
||||
|
||||
// Make proxy requests and wait up to 5 seconds before timing out
|
||||
app.Get("/proxy", func(c *fiber.Ctx) error {
|
||||
app.Get("/proxy", func(c fiber.Ctx) error {
|
||||
if err := proxy.DoTimeout(c, "http://localhost:3000", time.Second * 5); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -96,7 +96,7 @@ app.Get("/proxy", func(c *fiber.Ctx) error {
|
|||
})
|
||||
|
||||
// Make proxy requests, timeout a minute from now
|
||||
app.Get("/proxy", func(c *fiber.Ctx) error {
|
||||
app.Get("/proxy", func(c fiber.Ctx) error {
|
||||
if err := proxy.DoDeadline(c, "http://localhost", time.Now().Add(time.Minute)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -121,11 +121,11 @@ app.Use(proxy.Balancer(proxy.Config{
|
|||
"http://localhost:3002",
|
||||
"http://localhost:3003",
|
||||
},
|
||||
ModifyRequest: func(c *fiber.Ctx) error {
|
||||
ModifyRequest: func(c fiber.Ctx) error {
|
||||
c.Request().Header.Add("X-Real-IP", c.IP())
|
||||
return nil
|
||||
},
|
||||
ModifyResponse: func(c *fiber.Ctx) error {
|
||||
ModifyResponse: func(c fiber.Ctx) error {
|
||||
c.Response().Header.Del(fiber.HeaderServer)
|
||||
return nil
|
||||
},
|
||||
|
@ -143,7 +143,7 @@ app.Use(proxy.BalancerForward([]string{
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:----------------|:-----------------------------------------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:----------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Servers | `[]string` | Servers defines a list of `<scheme>://<host>` HTTP servers, which are used in a round-robin manner. i.e.: "https://foobar.com, http://www.foobar.com" | (Required) |
|
||||
| ModifyRequest | `fiber.Handler` | ModifyRequest allows you to alter the request. | `nil` |
|
||||
| ModifyResponse | `fiber.Handler` | ModifyResponse allows you to alter the response. | `nil` |
|
||||
|
|
|
@ -30,7 +30,7 @@ After you initiate your Fiber app, you can use the following possibilities:
|
|||
app.Use(recover.New())
|
||||
|
||||
// This panic will be caught by the middleware
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("I'm an error")
|
||||
})
|
||||
```
|
||||
|
@ -39,9 +39,9 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:------------------|:--------------------------------|:--------------------------------------------------------------------|:-------------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| EnableStackTrace | `bool` | EnableStackTrace enables handling stack trace. | `false` |
|
||||
| StackTraceHandler | `func(*fiber.Ctx, interface{})` | StackTraceHandler defines a function to handle stack trace. | defaultStackTraceHandler |
|
||||
| StackTraceHandler | `func(fiber.Ctx, interface{})` | StackTraceHandler defines a function to handle stack trace. | defaultStackTraceHandler |
|
||||
|
||||
## Default Config
|
||||
|
||||
|
|
|
@ -33,10 +33,10 @@ func main() {
|
|||
StatusCode: 301,
|
||||
}))
|
||||
|
||||
app.Get("/new", func(c *fiber.Ctx) error {
|
||||
app.Get("/new", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
app.Get("/new/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/new/*", func(c fiber.Ctx) error {
|
||||
return c.SendString("Wildcard: " + c.Params("*"))
|
||||
})
|
||||
|
||||
|
@ -55,7 +55,7 @@ curl http://localhost:3000/old/hello
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-----------|:------------------------|:---------------------------------------------------------------------------------------------------------------------------|:-----------------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Filter defines a function to skip middleware. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Filter defines a function to skip middleware. | `nil` |
|
||||
| Rules | `map[string]string` | Rules defines the URL path rewrite rules. The values captured in asterisk can be retrieved by index e.g. $1, $2 and so on. | Required |
|
||||
| StatusCode | `int` | The status code when redirecting. This is ignored if Redirect is disabled. | 302 Temporary Redirect |
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@ RequestID middleware for [Fiber](https://github.com/gofiber/fiber) that adds an
|
|||
|
||||
```go
|
||||
func New(config ...Config) fiber.Handler
|
||||
func FromContext(c *fiber.Ctx) string
|
||||
func FromContext(c fiber.Ctx) string
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
@ -42,7 +42,7 @@ app.Use(requestid.New(requestid.Config{
|
|||
Getting the request ID
|
||||
|
||||
```go
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
id := requestid.FromContext(c)
|
||||
log.Printf("Request ID: %s", id)
|
||||
return c.SendString("Hello, World!")
|
||||
|
@ -53,7 +53,7 @@ func handler(c *fiber.Ctx) error {
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:-----------|:------------------------|:--------------------------------------------------------------------------------------------------|:---------------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
|
||||
| Header | `string` | Header is the header key where to get/set the unique request ID. | "X-Request-ID" |
|
||||
| Generator | `func() string` | Generator defines a function to generate the unique identifier. | utils.UUID |
|
||||
|
||||
|
|
|
@ -16,7 +16,7 @@ func New(config ...Config) fiber.Handler
|
|||
|
||||
| Property | Type | Description | Default |
|
||||
|:---------|:------------------------|:-----------------------------------------------------------------------------------------------------|:-----------|
|
||||
| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip middleware. | `nil` |
|
||||
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip middleware. | `nil` |
|
||||
| Rules | `map[string]string` | Rules defines the URL path rewrite rules. The values captured in asterisk can be retrieved by index. | (Required) |
|
||||
|
||||
### Examples
|
||||
|
@ -38,10 +38,10 @@ func main() {
|
|||
},
|
||||
}))
|
||||
|
||||
app.Get("/new", func(c *fiber.Ctx) error {
|
||||
app.Get("/new", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
app.Get("/new/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/new/*", func(c fiber.Ctx) error {
|
||||
return c.SendString("Wildcard: " + c.Params("*"))
|
||||
})
|
||||
|
||||
|
|
|
@ -15,7 +15,7 @@ This middleware uses our [Storage](https://github.com/gofiber/storage) package t
|
|||
```go
|
||||
func New(config ...Config) *Store
|
||||
func (s *Store) RegisterType(i interface{})
|
||||
func (s *Store) Get(c *fiber.Ctx) (*Session, error)
|
||||
func (s *Store) Get(c fiber.Ctx) (*Session, error)
|
||||
func (s *Store) Delete(id string) error
|
||||
func (s *Store) Reset() error
|
||||
|
||||
|
@ -51,7 +51,7 @@ After you initiate your Fiber app, you can use the following possibilities:
|
|||
// This stores all of your app's sessions
|
||||
store := session.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Get session from storage
|
||||
sess, err := store.Get(c)
|
||||
if err != nil {
|
||||
|
|
|
@ -8,7 +8,7 @@ Skip middleware for [Fiber](https://github.com/gofiber/fiber) that skips a wrapp
|
|||
|
||||
## Signatures
|
||||
```go
|
||||
func New(handler fiber.Handler, exclude func(c *fiber.Ctx) bool) fiber.Handler
|
||||
func New(handler fiber.Handler, exclude func(c fiber.Ctx) bool) fiber.Handler
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
@ -26,18 +26,18 @@ After you initiate your Fiber app, you can use the following possibilities:
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Use(skip.New(BasicHandler, func(ctx *fiber.Ctx) bool {
|
||||
app.Use(skip.New(BasicHandler, func(ctx fiber.Ctx) bool {
|
||||
return ctx.Method() == fiber.MethodGet
|
||||
}))
|
||||
|
||||
app.Get("/", func(ctx *fiber.Ctx) error {
|
||||
app.Get("/", func(ctx fiber.Ctx) error {
|
||||
return ctx.SendString("It was a GET request!")
|
||||
})
|
||||
|
||||
log.Fatal(app.Listen(":3000"))
|
||||
}
|
||||
|
||||
func BasicHandler(ctx *fiber.Ctx) error {
|
||||
func BasicHandler(ctx fiber.Ctx) error {
|
||||
return ctx.SendString("It was not a GET request!")
|
||||
}
|
||||
```
|
||||
|
|
|
@ -50,7 +50,7 @@ func main() {
|
|||
h := func(c fiber.Ctx) error {
|
||||
=======
|
||||
|
||||
h := func(c *fiber.Ctx) error {
|
||||
h := func(c fiber.Ctx) error {
|
||||
>>>>>>> origin/master:docs/api/middleware/timeout.md
|
||||
sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms")
|
||||
if err := sleepWithContext(c.UserContext(), sleepTime); err != nil {
|
||||
|
@ -130,7 +130,7 @@ func main() {
|
|||
app := fiber.New()
|
||||
db, _ := gorm.Open(postgres.Open("postgres://localhost/foodb"), &gorm.Config{})
|
||||
|
||||
handler := func(ctx *fiber.Ctx) error {
|
||||
handler := func(ctx fiber.Ctx) error {
|
||||
tran := db.WithContext(ctx.UserContext()).Begin()
|
||||
|
||||
if tran = tran.Exec("SELECT pg_sleep(50)"); tran.Error != nil {
|
||||
|
|
|
@ -25,7 +25,7 @@ If you're using v2.32.0 or later, all you need to do is to implement a custom er
|
|||
If you're using v2.31.0 or earlier, the error handler will not capture 404 errors. Instead, you need to add a middleware function at the very bottom of the stack \(below all other functions\) to handle a 404 response:
|
||||
|
||||
```go title="Example"
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.Status(fiber.StatusNotFound).SendString("Sorry can't find that!")
|
||||
})
|
||||
```
|
||||
|
@ -66,7 +66,7 @@ To override the default error handler, you can override the default when providi
|
|||
|
||||
```go title="Example"
|
||||
app := fiber.New(fiber.Config{
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
ErrorHandler: func(c fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusInternalServerError).SendString(err.Error())
|
||||
},
|
||||
})
|
||||
|
@ -126,7 +126,7 @@ func main() {
|
|||
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
|
||||
}))
|
||||
hosts["api.localhost:3000"] = &Host{api}
|
||||
api.Get("/", func(c *fiber.Ctx) error {
|
||||
api.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("API")
|
||||
})
|
||||
//------
|
||||
|
@ -137,7 +137,7 @@ func main() {
|
|||
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
|
||||
}))
|
||||
hosts["blog.localhost:3000"] = &Host{blog}
|
||||
blog.Get("/", func(c *fiber.Ctx) error {
|
||||
blog.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Blog")
|
||||
})
|
||||
//---------
|
||||
|
@ -149,12 +149,12 @@ func main() {
|
|||
}))
|
||||
|
||||
hosts["localhost:3000"] = &Host{site}
|
||||
site.Get("/", func(c *fiber.Ctx) error {
|
||||
site.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Website")
|
||||
})
|
||||
// Server
|
||||
app := fiber.New()
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
host := hosts[c.Hostname()]
|
||||
if host == nil {
|
||||
return c.SendStatus(fiber.StatusNotFound)
|
||||
|
|
|
@ -19,7 +19,7 @@ It’s essential to ensure that Fiber catches all errors that occur while runnin
|
|||
<TabItem value="example" label="Example">
|
||||
|
||||
```go
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Pass error to Fiber
|
||||
return c.SendFile("file-does-not-exist")
|
||||
})
|
||||
|
@ -44,7 +44,7 @@ func main() {
|
|||
|
||||
app.Use(recover.New())
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
panic("This panic is caught by fiber")
|
||||
})
|
||||
|
||||
|
@ -55,7 +55,7 @@ func main() {
|
|||
You could use Fiber's custom error struct to pass an additional `status code` using `fiber.NewError()`. It's optional to pass a message; if this is left empty, it will default to the status code message \(`404` equals `Not Found`\).
|
||||
|
||||
```go title="Example"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// 503 Service Unavailable
|
||||
return fiber.ErrServiceUnavailable
|
||||
|
||||
|
@ -70,7 +70,7 @@ Fiber provides an error handler by default. For a standard error, the response i
|
|||
|
||||
```go title="Example"
|
||||
// Default error handler
|
||||
var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
|
||||
var DefaultErrorHandler = func(c fiber.Ctx, err error) error {
|
||||
// Status code defaults to 500
|
||||
code := fiber.StatusInternalServerError
|
||||
|
||||
|
@ -100,7 +100,7 @@ The following example shows how to display error pages for different types of er
|
|||
// Create a new fiber instance with custom config
|
||||
app := fiber.New(fiber.Config{
|
||||
// Override default error handler
|
||||
ErrorHandler: func(ctx *fiber.Ctx, err error) error {
|
||||
ErrorHandler: func(ctx fiber.Ctx, err error) error {
|
||||
// Status code defaults to 500
|
||||
code := fiber.StatusInternalServerError
|
||||
|
||||
|
|
|
@ -62,12 +62,12 @@ Group handlers can also be used as a routing path but they must have **Next** ad
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
handler := func(c *fiber.Ctx) error {
|
||||
handler := func(c fiber.Ctx) error {
|
||||
return c.SendStatus(fiber.StatusOK)
|
||||
}
|
||||
api := app.Group("/api") // /api
|
||||
|
||||
v1 := api.Group("/v1", func(c *fiber.Ctx) error { // middleware for /api/v1
|
||||
v1 := api.Group("/v1", func(c fiber.Ctx) error { // middleware for /api/v1
|
||||
c.Set("Version", "v1")
|
||||
return c.Next()
|
||||
})
|
||||
|
|
|
@ -65,7 +65,7 @@ import (
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Route().Name)
|
||||
}).Name("index")
|
||||
|
||||
|
@ -81,11 +81,11 @@ func main() {
|
|||
return nil
|
||||
})
|
||||
|
||||
app.Get("/add/user", func(c *fiber.Ctx) error {
|
||||
app.Get("/add/user", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Route().Name)
|
||||
}).Name("addUser")
|
||||
|
||||
app.Delete("/destroy/user", func(c *fiber.Ctx) error {
|
||||
app.Delete("/destroy/user", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Route().Name)
|
||||
}).Name("destroyUser")
|
||||
|
||||
|
|
|
@ -23,17 +23,17 @@ Route paths, combined with a request method, define the endpoints at which reque
|
|||
|
||||
```go
|
||||
// This route path will match requests to the root route, "/":
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("root")
|
||||
})
|
||||
|
||||
// This route path will match requests to "/about":
|
||||
app.Get("/about", func(c *fiber.Ctx) error {
|
||||
app.Get("/about", func(c fiber.Ctx) error {
|
||||
return c.SendString("about")
|
||||
})
|
||||
|
||||
// This route path will match requests to "/random.txt":
|
||||
app.Get("/random.txt", func(c *fiber.Ctx) error {
|
||||
app.Get("/random.txt", func(c fiber.Ctx) error {
|
||||
return c.SendString("random.txt")
|
||||
})
|
||||
```
|
||||
|
@ -59,28 +59,28 @@ The routing also offers the possibility to use optional parameters, for the name
|
|||
|
||||
```go
|
||||
// Parameters
|
||||
app.Get("/user/:name/books/:title", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:name/books/:title", func(c fiber.Ctx) error {
|
||||
fmt.Fprintf(c, "%s\n", c.Params("name"))
|
||||
fmt.Fprintf(c, "%s\n", c.Params("title"))
|
||||
return nil
|
||||
})
|
||||
// Plus - greedy - not optional
|
||||
app.Get("/user/+", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/+", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("+"))
|
||||
})
|
||||
|
||||
// Optional parameter
|
||||
app.Get("/user/:name?", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/:name?", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("name"))
|
||||
})
|
||||
|
||||
// Wildcard - greedy - optional
|
||||
app.Get("/user/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/user/*", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("*"))
|
||||
})
|
||||
|
||||
// This route path will match requests to "/v1/some/resource/name:customVerb", since the parameter character is escaped
|
||||
app.Get(`/v1/some/resource/name\:customVerb`, func(c *fiber.Ctx) error {
|
||||
app.Get(`/v1/some/resource/name\:customVerb`, func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, Community")
|
||||
})
|
||||
```
|
||||
|
@ -95,7 +95,7 @@ All special parameter characters can also be escaped with `"\\"` and lose their
|
|||
|
||||
```go
|
||||
// http://localhost:3000/plantae/prunus.persica
|
||||
app.Get("/plantae/:genus.:species", func(c *fiber.Ctx) error {
|
||||
app.Get("/plantae/:genus.:species", func(c fiber.Ctx) error {
|
||||
fmt.Fprintf(c, "%s.%s\n", c.Params("genus"), c.Params("species"))
|
||||
return nil // prunus.persica
|
||||
})
|
||||
|
@ -103,7 +103,7 @@ app.Get("/plantae/:genus.:species", func(c *fiber.Ctx) error {
|
|||
|
||||
```go
|
||||
// http://localhost:3000/flights/LAX-SFO
|
||||
app.Get("/flights/:from-:to", func(c *fiber.Ctx) error {
|
||||
app.Get("/flights/:from-:to", func(c fiber.Ctx) error {
|
||||
fmt.Fprintf(c, "%s-%s\n", c.Params("from"), c.Params("to"))
|
||||
return nil // LAX-SFO
|
||||
})
|
||||
|
@ -113,7 +113,7 @@ Our intelligent router recognizes that the introductory parameter characters sho
|
|||
|
||||
```go
|
||||
// http://localhost:3000/shop/product/color:blue/size:xs
|
||||
app.Get("/shop/product/color::color/size::size", func(c *fiber.Ctx) error {
|
||||
app.Get("/shop/product/color::color/size::size", func(c fiber.Ctx) error {
|
||||
fmt.Fprintf(c, "%s:%s\n", c.Params("color"), c.Params("size"))
|
||||
return nil // blue:xs
|
||||
})
|
||||
|
@ -170,7 +170,7 @@ Constraints aren't validation for parameters. If constraint aren't valid for par
|
|||
<TabItem value="single-constraint" label="Single Constraint">
|
||||
|
||||
```go
|
||||
app.Get("/:test<min(5)>", func(c *fiber.Ctx) error {
|
||||
app.Get("/:test<min(5)>", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("test"))
|
||||
})
|
||||
|
||||
|
@ -185,7 +185,7 @@ app.Get("/:test<min(5)>", func(c *fiber.Ctx) error {
|
|||
|
||||
You can use `;` for multiple constraints.
|
||||
```go
|
||||
app.Get("/:test<min(100);maxLen(5)>", func(c *fiber.Ctx) error {
|
||||
app.Get("/:test<min(100);maxLen(5)>", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("test"))
|
||||
})
|
||||
|
||||
|
@ -203,7 +203,7 @@ app.Get("/:test<min(100);maxLen(5)>", func(c *fiber.Ctx) error {
|
|||
|
||||
Fiber precompiles regex query when to register routes. So there're no performance overhead for regex constraint.
|
||||
```go
|
||||
app.Get(`/:date<regex(\d{4}-\d{2}-\d{2})>`, func(c *fiber.Ctx) error {
|
||||
app.Get(`/:date<regex(\d{4}-\d{2}-\d{2})>`, func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("date"))
|
||||
})
|
||||
|
||||
|
@ -229,7 +229,7 @@ You should use `\\` before routing-specific characters when to use datetime cons
|
|||
You can impose constraints on optional parameters as well.
|
||||
|
||||
```go
|
||||
app.Get("/:test<int>?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:test<int>?", func(c fiber.Ctx) error {
|
||||
return c.SendString(c.Params("test"))
|
||||
})
|
||||
// curl -X GET http://localhost:3000/42
|
||||
|
@ -247,7 +247,7 @@ Functions that are designed to make changes to the request or response are calle
|
|||
**Example of a middleware function**
|
||||
|
||||
```go
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
// Set a custom header on all responses:
|
||||
c.Set("X-Custom-Header", "Hello, World")
|
||||
|
||||
|
@ -255,7 +255,7 @@ app.Use(func(c *fiber.Ctx) error {
|
|||
return c.Next()
|
||||
})
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
|
|
@ -39,7 +39,7 @@ The `Render` method is linked to the [**ctx.Render\(\)**](../api/ctx.md#render)
|
|||
If the Fiber config option `PassLocalsToViews` is enabled, then all locals set using `ctx.Locals(key, value)` will be passed to the template.
|
||||
|
||||
```go
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.Render("index", fiber.Map{
|
||||
"hello": "world",
|
||||
});
|
||||
|
@ -82,7 +82,7 @@ func main() {
|
|||
app := fiber.New(fiber.Config{
|
||||
Views: engine,
|
||||
})
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
// Render index template
|
||||
return c.Render("index", fiber.Map{
|
||||
"Title": "Hello, World!",
|
||||
|
|
|
@ -81,7 +81,7 @@ func main() {
|
|||
|
||||
app := fiber.New(fiber.Config{
|
||||
// Global custom error handler
|
||||
ErrorHandler: func(c *fiber.Ctx, err error) error {
|
||||
ErrorHandler: func(c fiber.Ctx, err error) error {
|
||||
return c.Status(fiber.StatusBadRequest).JSON(GlobalErrorHandlerResp{
|
||||
Success: false,
|
||||
Message: err.Error(),
|
||||
|
@ -95,7 +95,7 @@ func main() {
|
|||
return fl.Field().Int() >= 12 && fl.Field().Int() <= 18
|
||||
})
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
user := &User{
|
||||
Name: c.Query("name"),
|
||||
Age: c.QueryInt("age"),
|
||||
|
|
|
@ -21,12 +21,12 @@ go get github.com/gofiber/fiber/v2
|
|||
```
|
||||
|
||||
### Zero Allocation
|
||||
Some values returned from \***fiber.Ctx** are **not** immutable by default.
|
||||
Some values returned from **fiber.Ctx** are **not** immutable by default.
|
||||
|
||||
Because fiber is optimized for **high-performance**, values returned from **fiber.Ctx** are **not** immutable by default and **will** be re-used across requests. As a rule of thumb, you **must** only use context values within the handler, and you **must not** keep any references. As soon as you return from the handler, any values you have obtained from the context will be re-used in future requests and will change below your feet. Here is an example:
|
||||
|
||||
```go
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
// Variable is only valid within this handler
|
||||
result := c.Params("foo")
|
||||
|
||||
|
@ -37,7 +37,7 @@ func handler(c *fiber.Ctx) error {
|
|||
If you need to persist such values outside the handler, make copies of their **underlying buffer** using the [copy](https://pkg.go.dev/builtin/#copy) builtin. Here is an example for persisting a string:
|
||||
|
||||
```go
|
||||
func handler(c *fiber.Ctx) error {
|
||||
func handler(c fiber.Ctx) error {
|
||||
// Variable is only valid within this handler
|
||||
result := c.Params("foo")
|
||||
|
||||
|
@ -54,7 +54,7 @@ func handler(c *fiber.Ctx) error {
|
|||
We created a custom `CopyString` function that does the above and is available under [gofiber/utils](https://github.com/gofiber/fiber/tree/master/utils).
|
||||
|
||||
```go
|
||||
app.Get("/:foo", func(c *fiber.Ctx) error {
|
||||
app.Get("/:foo", func(c fiber.Ctx) error {
|
||||
// Variable is now immutable
|
||||
result := utils.CopyString(c.Params("foo"))
|
||||
|
||||
|
@ -84,7 +84,7 @@ import "github.com/gofiber/fiber/v2"
|
|||
func main() {
|
||||
app := fiber.New()
|
||||
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
|
||||
|
@ -108,19 +108,19 @@ Route definition takes the following structures:
|
|||
|
||||
```go
|
||||
// Function signature
|
||||
app.Method(path string, ...func(*fiber.Ctx) error)
|
||||
app.Method(path string, ...func(fiber.Ctx) error)
|
||||
```
|
||||
|
||||
- `app` is an instance of **Fiber**
|
||||
- `Method` is an [HTTP request method](https://docs.gofiber.io/api/app#route-handlers): `GET`, `PUT`, `POST`, etc.
|
||||
- `path` is a virtual path on the server
|
||||
- `func(*fiber.Ctx) error` is a callback function containing the [Context](https://docs.gofiber.io/api/ctx) executed when the route is matched
|
||||
- `func(fiber.Ctx) error` is a callback function containing the [Context](https://docs.gofiber.io/api/ctx) executed when the route is matched
|
||||
|
||||
**Simple route**
|
||||
|
||||
```go
|
||||
// Respond with "Hello, World!" on root path, "/"
|
||||
app.Get("/", func(c *fiber.Ctx) error {
|
||||
app.Get("/", func(c fiber.Ctx) error {
|
||||
return c.SendString("Hello, World!")
|
||||
})
|
||||
```
|
||||
|
@ -130,7 +130,7 @@ app.Get("/", func(c *fiber.Ctx) error {
|
|||
```go
|
||||
// GET http://localhost:8080/hello%20world
|
||||
|
||||
app.Get("/:value", func(c *fiber.Ctx) error {
|
||||
app.Get("/:value", func(c fiber.Ctx) error {
|
||||
return c.SendString("value: " + c.Params("value"))
|
||||
// => Get request with value: hello world
|
||||
})
|
||||
|
@ -141,7 +141,7 @@ app.Get("/:value", func(c *fiber.Ctx) error {
|
|||
```go
|
||||
// GET http://localhost:3000/john
|
||||
|
||||
app.Get("/:name?", func(c *fiber.Ctx) error {
|
||||
app.Get("/:name?", func(c fiber.Ctx) error {
|
||||
if c.Params("name") != "" {
|
||||
return c.SendString("Hello " + c.Params("name"))
|
||||
// => Hello john
|
||||
|
@ -155,7 +155,7 @@ app.Get("/:name?", func(c *fiber.Ctx) error {
|
|||
```go
|
||||
// GET http://localhost:3000/api/user/john
|
||||
|
||||
app.Get("/api/*", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/*", func(c fiber.Ctx) error {
|
||||
return c.SendString("API path: " + c.Params("*"))
|
||||
// => API path: user/john
|
||||
})
|
||||
|
|
|
@ -27,12 +27,12 @@ func (app *App) All(path string, handlers ...Handler) Router
|
|||
|
||||
```go title="Examples"
|
||||
// Simple GET handler
|
||||
app.Get("/api/list", func(c *fiber.Ctx) error {
|
||||
app.Get("/api/list", func(c fiber.Ctx) error {
|
||||
return c.SendString("I'm a GET request!")
|
||||
})
|
||||
|
||||
// Simple POST handler
|
||||
app.Post("/api/register", func(c *fiber.Ctx) error {
|
||||
app.Post("/api/register", func(c fiber.Ctx) error {
|
||||
return c.SendString("I'm a POST request!")
|
||||
})
|
||||
```
|
||||
|
@ -45,25 +45,25 @@ func (app *App) Use(args ...interface{}) Router
|
|||
|
||||
```go title="Examples"
|
||||
// Match any request
|
||||
app.Use(func(c *fiber.Ctx) error {
|
||||
app.Use(func(c fiber.Ctx) error {
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match request starting with /api
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Match requests starting with /api or /home (multiple-prefix support)
|
||||
app.Use([]string{"/api", "/home"}, func(c *fiber.Ctx) error {
|
||||
app.Use([]string{"/api", "/home"}, func(c fiber.Ctx) error {
|
||||
return c.Next()
|
||||
})
|
||||
|
||||
// Attach multiple handlers
|
||||
app.Use("/api", func(c *fiber.Ctx) error {
|
||||
app.Use("/api", func(c fiber.Ctx) error {
|
||||
c.Set("X-Custom-Header", random.String(32))
|
||||
return c.Next()
|
||||
}, func(c *fiber.Ctx) error {
|
||||
}, func(c fiber.Ctx) error {
|
||||
return c.Next()
|
||||
})
|
||||
```
|
||||
|
|
Loading…
Reference in New Issue