Fiber
is inspired by the most popular Web
framework Express
on the Internet. We combine the usability of Express
and the raw performance of Go
. If you have ever built a Web
application using Node.js
(using Express or similar framework), then many methods and principles should be very easy to understand for you.
Quick Start
Installation
Make sure to have Go 1.17
or higher installed.
Initialize your project by creating a folder and running go mod init github.com/your/repo
inside the folder, then install Fiber using the go get
command:
go get -u github.com/gofiber/fiber/v2
Hello World
package main
// Import the fiber package
import "github.com/gofiber/fiber/v2"
func main() {
// Define the fiber app
app := fiber.New()
// Define the http route
app.Get("/", func(c *fiber.Ctx) error {
// Return hello world as a string
return c.SendString("Hello, World ?!")
})
// Listen on port 3000
app.Listen(":3000")
}
Access via: http://localhost:3000/
Basic Routing
Fiber basic routing example
func main() {
app := fiber.New()
// GET /api/register
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 {
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 {
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 {
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 {
msg := fmt.Sprintf("Hello, %s ?!", c.Params("name"))
return c.SendString(msg) // => Hello john ?!
})
log.Fatal(app.Listen(":3000"))
}
Serving Static Files
Set up static file serving
func main() {
app := fiber.New()
app.Static("/", "./public")
// => http://localhost:3000/js/script.js
// => http://localhost:3000/css/style.css
app.Static("/prefix", "./public")
// => http://localhost:3000/prefix/js/script.js
// => http://localhost:3000/prefix/css/style.css
app.Static("*", "./public/index.html")
// => http://localhost:3000/any/path/shows/index/html
log.Fatal(app.Listen(":3000"))
}
Middleware
Enhance the ability to handle HTTP requests through middleware.
func main() {
app := fiber.New()
// Match any route, here customize middleware using a closure function
app.Use(func(c *fiber.Ctx) error {
fmt.Println("? First handler")
// Continue to handle the next middleware or route function
return c.Next()
})
// Match routes starting with /api
app.Use("/api", func(c *fiber.Ctx) error {
fmt.Println("? Second handler")
return c.Next()
})
// Use the built-in middleware for handling exceptions
app.Use(recover.New())
// GET /api/register
app.Get("/api/list", func(c *fiber.Ctx) error {
fmt.Println("? Last handler")
return c.SendString("Hello, World ?!")
})
log.Fatal(app.Listen(":3000"))
}
Template Engine
If the template engine is not set, Fiber
defaults to using html/template.
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/template/pug"
)
func main() {
// Set the template engine
app := fiber.New(fiber.Config{
Views: pug.New("./views", ".pug"),
})
app.Get("/", func(c *fiber.Ctx) error {
// Render the ./views/home.pug template using fiber.map template parameters
return c.Render("home", fiber.Map{
"title": "Homepage",
"year": 1999,
})
})
log.Fatal(app.Listen(":3000"))
}
Cross-Origin Resource Sharing (CORS) Middleware
Middleware for CORS in Fiber, can enable cross-origin resource sharing with various options to prevent CORS attacks.
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
func main() {
app := fiber.New()
// Default CORS configuration
app.Use(cors.New())
// Or customize CORS parameters to allow requests from certain domains
app.Use(cors.New(cors.Config{
AllowOrigins: "https://www.tizi365.com, https://tizi365.com",
AllowHeaders: "Origin, Content-Type, Accept",
}))
log.Fatal(app.Listen(":3000"))
}
Check CORS by passing any domain in the Origin
header:
curl -H "Origin: https://www.tizi365.com" --verbose http://localhost:3000
Custom 404 Response
func main() {
app := fiber.New()
app.Static("/", "./public")
app.Get("/demo", func(c *fiber.Ctx) error {
return c.SendString("This is a demo!")
})
app.Post("/register", func(c *fiber.Ctx) error {
return c.SendString("Welcome!")
})
// The last referenced middleware will match all requests, including 404
app.Use(func(c *fiber.Ctx) error {
// Other handling logic
// Return 404 status
return c.SendStatus(404)
// => 404 "Not Found"
})
log.Fatal(app.Listen(":3000"))
}
JSON Response
Example of Fiber returning JSON data.
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
app := fiber.New()
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 {
return c.JSON(fiber.Map{
"success": true,
"message": "Hi John!",
})
// => {"success":true, "message":"Hi John!"}
})
log.Fatal(app.Listen(":3000"))
}
Recovery Middleware
Intercept panic errors to prevent program crash and exit.
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
)
func main() {
app := fiber.New()
// Use the panic middleware to intercept panic exceptions
app.Use(recover.New())
app.Get("/", func(c *fiber.Ctx) error {
panic("normally this would crash your app")
})
log.Fatal(app.Listen(":3000"))
}
Benchmark
[
Limitations
- Due to the use of unsafe features in Fiber, it may be incompatible with the latest Go versions. Fiber 2.40.0 has been tested on Go versions 1.17 to 1.21.
- Fiber is not compatible with the net/http interface. This means that you cannot directly use projects such as gqlgen, go-swagger, or any other projects belonging to the net/http ecosystem.