Go by Example: Building APIs with Fiber
Go 1.23
Create fast and scalable web applications with Fiber, an Express-inspired framework for Go. This example demonstrates Fiber's familiar API for routing and handling requests, making it an excellent choice for developers coming from Node.js.
Code
package main
import "github.com/gofiber/fiber/v2"
func main() {
// Initialize a new Fiber app
app := fiber.New()
// Define a simple GET route
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
// Define a route that returns JSON
app.Get("/json", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"success": true,
"message": "Hi Fiber!",
})
})
// Define a POST route with parameters
app.Post("/api/register", func(c *fiber.Ctx) error {
// ... registration logic would go here
return c.SendStatus(200)
})
// Start the server on port 3000
app.Listen(":3000")
}Explanation
Fiber is a Go web framework built on top of Fasthttp, the fastest HTTP engine for Go. It is designed to ease things up for fast development with zero memory allocation and performance in mind. Its API is inspired by Express.js, making it instantly familiar to Node.js developers.
Why choose Fiber?
- Performance: Fiber is optimized for speed and low memory usage, often outperforming `net/http` based frameworks in benchmarks.
- Express-like API: Methods like `app.Get`, `app.Post`, and `c.Send` mirror the Express.js syntax, lowering the learning curve.
- Robust Routing: Supports parameters, grouping, and static files out of the box.
Code Breakdown
7
fiber.New() creates a new Fiber application instance. You can pass a config struct here to customize behavior (e.g., setting the maximum body size or enabling pre-forking).
10
app.Get registers a handler for HTTP GET requests. The handler function receives a *fiber.Ctx context, which holds all request and response data. Unlike net/http, handlers return an error.
11
c.SendString sends a plain text response. Fiber automatically sets the Content-Type header to "text/plain; charset=utf-8".
16
c.JSON sends a JSON response. fiber.Map is a convenient alias for map[string]interface{}, allowing you to construct JSON objects inline without defining a struct.
29
app.Listen starts the HTTP server on the specified address. It blocks the main goroutine and listens for incoming connections.

