Getting started with Fiber

This article was originally published at https://amalshaji.com/getting-started-with-fiber/

What is Fiber?

Fiber is a relatively new framework for golang, which has gained a huge fanbase in a quick time. It is built on top of FastHTTP, the fastest HTTP engine for Go (Upto 10x faster then net/http). FastHTTP makes fiber one of the fastest Go web frameworks out there.

See the Fiber benchmark against various go players.

benchmark.png

Fiber APIs are focussed on simplicity and are similar to expressjs, which makes it easy for people switching from Nodejs to Go.

Installing Fiber

This post assumes that you have already installed Golang. If not, go to https://golang.org/ and click download. The website provides installation instructions for each operating system.

Manual installation

Start by creating a folder of your choice. Once inside the project directory, initialize go modules in it by running.

go mod init github.com/amalshaji/fiber-intro


Now install Fiber-v2,

go get -u github.com/gofiber/fiber/v2

Using Fiber cli

Install fiber-cli

go get -u github.com/gofiber/cli/fiber

Once installed, create a new fiber project.

fiber new fiber-intro

Fiber-cli will create a new project with module name defaulted to project name, i.e., fiber-intro. To specify a module name, run,

fiber new fiber-intro github.com/amalshaji/fiber-demo

Hello Fiber

Create a main.go file inside the project directory.

// main.go

package main

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

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

  app.Use(logger.New())

  app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Hellođź‘‹")
  })

  log.Fatal(app.Listen(":3000"))
}

We have successfully created our first fiber program. Let's see what each line means.

app := fiber.New()

This creates a new fiber application with a default configuration. You can set configuration like BodyLimit, ServerHeader, etc.

app := fiber.New(fiber.Config{
        BodyLimit: 20 * 1024 * 1024,
    })

This limits the request body size to 20MB. Read more about fiber app configuration here.

app.Use(logger.New())

app.Use() is used to add middlewares to our fiber application. Middlewares are special functions that receive the request before any handler. Middlewares can process requests and do various operations like logging, rate-limiting, etc. Fiber supports many builtin middlewares and community-supported ones, they include,

  • Logger
  • Cache
  • CORS
  • CSRF
  • Limiter

Check out the list of fiber middlewares here.

Order matters in fiber application. If you define logger middleware after all a particular route, the route won't be logged.

app.Get("/", func(c *fiber.Ctx) error {
  return c.SendString("Hellođź‘‹")
})

This is how we define a route in fiber. The fiber app supports GET, POST, PUT, DELETE...The Get method takes in a path as the first argument and multiple handlers as the second. Usually, we define only one handler.

The fiber handler takes in the context of request and returns an error. The above Get method can be rewritten as,

func HomePage(c *fiber.Ctx) error {
    return c.SendString("Hellođź‘‹")
}

app.Get("/", HomePage)

You can return data in various formats.

  // send a string as response
  return c.SendString("Hellođź‘‹")

  // This download the file to the user
  return c.Download("./static/filename.jpg")

  // More complex response.
  // Sends specified status codes and JSON response using
  // fiber.Map
    return c.Status(fiber.StatusAccepted).JSON(fiber.Map{
        "message": "ok",
  })

  // Or the user can send a json as a struct
    type response struct {
        message string  `json:"message"`
        login   bool    `json:"login"`
    }
    var resp response

    return c.JSON(resp)

Read more about it in the context package.

All the imports should be handled by the IDE. Popular IDE's like VSCode and Goland works perfectly. In case you're having trouble with VSCode, make sure they go formatting tool is set to goimports. I prefer Goland because of its better handling of packages with the same names and many other features.

app.Listen(":3000")

This is the port where our app runs. To run the application, run, go run main.go. For a development environment, it is suggested to setup hot-reloading, which restarts the app on change.

If you have fiber-cli(fiber) installed, just run fiber dev to start application in development mode. You can also enable hot-reloading by installing air and run air -d for debugging (this will print fiber logs to stdout).

Once the app is running, navigate to http://localhost:3000 from your browser or curl, and you should see the output.

hello.PNG

Congratulations🎉🎉, you're now ready to write your fiber app. If you need more help, head over to the fiber website or the join fiber discord(the fiber community is very active in resolving issues). Drop a star if you support the fiber project.

Explore unique projects by fiber community: recipes

Stay tuned. I will be writing more about fiber.

No Comments Yet