DEV Community

Cover image for 🚀 Fiber v1.8. What's new, updated and re-thinked?
Vic Shóstak
Vic Shóstak

Posted on • Edited on

🚀 Fiber v1.8. What's new, updated and re-thinked?

Introduction

Hi, Fiber community! 👋 With a little delay, but let me introduce the new major version of Fiber Go web framework – v1.8.

💭 Please note: official Fiber docs may not contains extensive description for some changes. Don't worry, authors are working right now for it.

📝 Table of contents

New life of Middlewares

A willful decision was made and now... all Fiber middlewares are put in their own Go package middleware with huge improvements!

If you want to install/update Fiber with middlewares, run command:

go get -u github.com/gofiber/fiber/...
Enter fullscreen mode Exit fullscreen mode

And use it on import section (after main package):

// ...

import (
    "github.com/gofiber/fiber"
    "github.com/gofiber/fiber/middleware" // add middleware package to project
)

// ...
Enter fullscreen mode Exit fullscreen mode

OK. Let's see what comes out of it! 😉

✅ middleware.BasicAuth()

Provides a very simple (but useful sometimes) authentication:

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

    // Set middleware config
    config := middleware.BasicAuthConfig{
        Users: fiber.Map{
            "john":  "doe",
            "admin": "123456",
        },
    }

    // Using BasicAuth middleware with config
    app.Use(middleware.BasicAuth(config))

    // Route for success authenticate
    app.Get("/", func(c *fiber.Ctx) {
        c.Send("You are authorized!")
    })

    app.Listen(3000)
}
Enter fullscreen mode Exit fullscreen mode

Check, how it works on console (by curl):

curl --user john:doe http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

✅ middleware.CORS()

CORS middleware implements Cross-Origin Resource Sharing specification. It's extremely useful middleware for work with frontend, when you build REST API.

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

    // Using CORS middleware
    app.Use(middleware.CORS())

    // ...
}
Enter fullscreen mode Exit fullscreen mode

And now, run on console:

curl -H "Origin: http://example.com" --verbose http://localhost:3000
Enter fullscreen mode Exit fullscreen mode

✅ middleware.Limiter()

This middleware can limit repeated requests to public APIs and/or endpoints. For example, let's limit the number of requests to a maximum of 2 per 10 seconds:

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

    // Max 2 requests per 10 seconds
    config := middleware.LimiterConfig{
        Timeout: 10,
        Max:     2,
    }

    // Using Limiter middleware with config
    app.Use(middleware.Limiter(config))

    // ...
}
Enter fullscreen mode Exit fullscreen mode

✅ middleware.Logger()

Built-in middleware for logs the information about each HTTP request.

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

    // If you want to change default Logger config
    config := middleware.LoggerConfig{
      Format:     "${time} - ${method} ${path}\n",
      TimeFormat: "Mon, 2 Jan 2006 15:04:05 MST",
    }

    // Using Logger middleware with config
    app.Use(middleware.Logger(config))

    // ...
}
Enter fullscreen mode Exit fullscreen mode

✅ middleware.RequestID()

This middleware ca add an identifier to the request using X-Request-ID header:

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

    // Using RequestID middleware
    app.Use(middleware.RequestID())

    // ...
}
Enter fullscreen mode Exit fullscreen mode

It generates and sets X-Request-ID header with UUID like:

6ba7b810-9dad-11d1-80b4-00c04fd430c8
Enter fullscreen mode Exit fullscreen mode

✅ middleware.Helmet()

Helmet middleware provides protection against:

  • Cross-Site Scripting (XSS) attack.
  • Content type sniffing.
  • Clickjacking.
  • Insecure connection.
  • And other code injection attacks.
func main() {
    app := fiber.New()

    // Using Helmet middleware
    app.Use(middleware.Helmet())

    // ...
}
Enter fullscreen mode Exit fullscreen mode

Fiber updates

New, Updated & Re-thinked

New features, some updates and re-thinks functions for you 👇

✅ Range() method for Ctx

This struct contain the type and a slice of ranges will be returned:

// Range: bytes=500-700, 700-900

app.Get("/", func(c *fiber.Ctx) {
  b := c.Range(1000)

  if b.Type == "bytes" {
    for r := range r.Ranges {
      fmt.Println(r)
      // => [500, 700]
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

✅ Compress() method for Ctx

With this method you can easily enable/disable compression within handlers.

func main() {
    // Init app and set config
    app := fiber.New(&fiber.Settings{
      Compression: true, // enable global compression
    })

    // Route with compression
    app.Get("/compressed", func(c *fiber.Ctx) {
      c.Send("Hello, compressed World!") // compressed
    })

    // Route without compression
    app.Get("/not-compressed", func(c *fiber.Ctx) {
      c.Compress(false)                      // disable compression
      c.Send("Hello, not compressed World!") // not compressed
    })

    // ...
}
Enter fullscreen mode Exit fullscreen mode

ℹ️ Compression option for Settings

Enables GZip or Deflate compression for all responses:

app.Settings.Compression = true
Enter fullscreen mode Exit fullscreen mode

ℹ️ Immutable option for Settings

When enabled, all values returned by context methods are immutable:

app.Settings.Immutable = true
Enter fullscreen mode Exit fullscreen mode

By default, they are valid until you return from the handler.

Re-named list

🔁 Settings.ViewFolder -> Settings.TemplateFolder
🔁 Settings.ViewEngine -> Settings.TemplateEngine
🔁 Settings.ViewExtension -> Settings.TemplateExtension

💬 Do you like Fiber? Tell about it!

Fiber authors are always listening to its users in issues and all over the Internet. Therefore, it would be great, if you could share your opinion or/and experience with Fiber to authors in GitHub repository!

[...] because it's only right way to create a fast, flexible and friendly Go web framework for any tasks, deadlines and developer skills!

— Fiber Authors

Do you like Fiber?

Your assistance to project 👍

  1. Add a GitHub Star to project.
  2. Tweet about Fiber on your Twitter.
  3. Help to translate README and API Docs to another language (at this moment, Fiber was translated to 10 languages).

Photo by

[Title] Vic Shóstak https://github.com/koddr
[1, 2] Ashley McNamara https://github.com/ashleymcnamara/gophers

P.S.

If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻

❗️ You can support me on Boosty, both on a permanent and on a one-time basis. All proceeds from this way will go to support my OSS projects and will energize me to create new products and articles for the community.

support me on Boosty

And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy!

My main projects that need your help (and stars) 👇

  • 🔥 gowebly: A next-generation CLI tool that makes it easy to create amazing web applications with Go on the backend, using htmx, hyperscript or Alpine.js and the most popular CSS frameworks on the frontend.
  • create-go-app: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.

Other my small projects: yatr, gosl, json2csv, csv2api.

Top comments (9)

Collapse
 
jitheshkt profile image
Jithesh. KT

Can you share an example CRUD API with MySQL and Fiber? Can't find anything online :(

Collapse
 
koddr profile image
Vic Shóstak

Hi! 👋 Thx for interesting Fiber.

I'm planning my next article's series like "Create REST API with Fiber and PostgreSQL". Maybe I will add some notes about working with MySQL to there.

Stay tuned! 😉

Collapse
 
jitheshkt profile image
Jithesh. KT

Nice! I've already started working on a side project with same stack. I am new to go. Have experience in express. Fiber is a life saver for developers like myself who is looking forward to learn something new. Cheers!

Thread Thread
 
koddr profile image
Vic Shóstak

Enjoy! :D

Collapse
 
tudorhulban profile image
Tudor Hulban

Hi! Maybe you could include a JWT example after basic auth. Thank you

Thread Thread
 
koddr profile image
Vic Shóstak

Hello! Yep, good point, thx.

We're preparing example for using JWT in our repo: github.com/gofiber/jwt (coming soon).

Thread Thread
 
starlordmtkf profile image
Ray Mayemir

Hi! I'm added simple implementation jwt middleware and sended pull req.

Can you comment and give requirements or reject it for any reason) tnx! :)

Thread Thread
 
fenny profile image
Fenny • Edited

Hi Ray, sorry for the late reply we will take a look at your PR tomorrow morning! Thanks!

Collapse
 
jeyarajcs profile image
jeyaraj

Awesome...
Eargely waiting for Fiber with MongoDB Examples.