DEV Community

Cover image for Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?
Vic Shóstak
Vic Shóstak

Posted on • Updated on

Fiber released v1.7! 🎉 What's new and is it still fast, flexible and friendly?

Introduction

Good Friday, everybody! 👋 It's a great day for upgrades and even more so for good ones. So, I'd like to suggest you go to a new level of Fiber Go web framework — new version v1.7.

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

📝 Table of contents

Official Fiber logo

First of all, Fiber v1.7 have a new awesome logo:

Fiber v1.7 logo

Thanks to Rasmus Andersen for great open source font called Inter 🥰

New features

OK. Let's go to another new features! 👇

✅ Render() method

Add support for template engines:

You can setup template engine before initiation app:

app := fiber.New(&fiber.Settings{
  TemplateEngine:    "mustache",
  TemplateFolder:    "./views",
  TemplateExtension: ".tmpl",
})
Enter fullscreen mode Exit fullscreen mode

Or after initiation:

app.Settings.TemplateEngine = "mustache"
app.Settings.TemplateFolder = "./views"
app.Settings.TemplateExtension = ".tmpl"
Enter fullscreen mode Exit fullscreen mode

And now, you can call template ./views/home.tmpl like this:

app.Get("/", func(c *fiber.Ctx) {
  c.Render("home", fiber.Map{
    "title": "Homepage",
    "year":  1999,
  })
})
Enter fullscreen mode Exit fullscreen mode

✅ Error() and Next(err) methods

Now, you may contains the Error information, that thrown by a panic or passed via the Next(err) method:

app.Get("/api/user", func (c *fiber.Ctx) {
  if err := c.JSON(&User); err != nil {
    c.Next(err) 
    // => if something went wrong here, we can handle it
  }
})

app.Use("/api", func(c *fiber.Ctx) {
  c.Set("Content-Type", "application/json")
  c.Status(500).Send(c.Error())
})
Enter fullscreen mode Exit fullscreen mode

✅ BodyParser() method

Binds the request body to a struct:

// curl -X POST -H "Content-Type: application/json" \ 
//   --data '{"name":"john","pass":"doe"}' localhost:3000

// curl -X POST -H "Content-Type: application/xml" \ 
//   --data '<Login><name>john</name><pass>doe</pass><Login>' localhost:3000

// curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
//   --data 'name=john&pass=doe' localhost:3000

// curl -v -F name=john -F pass=doe localhost:3000

type Person struct {
  Name string `json:"name" xml:"name" form:"name"`
  Pass string `json:"pass" xml:"pass" form:"pass"`
}

app.Post("/", func(c *fiber.Ctx) {
  var person Person

  if err := c.BodyParser(&person); err != nil {
      // Handle error
  }

  // Do something with person.Name or person.Pass
})
Enter fullscreen mode Exit fullscreen mode

✅ Group() method

Add chain function for groupping routes:

api := app.Group("/api", cors())  // /api

v1 := api.Group("/v1", mysql())   // /api/v1
v1.Get("/list", handler)          // /api/v1/list
v1.Get("/user", handler)          // /api/v1/user

v2 := api.Group("/v2", mongodb()) // /api/v2
v2.Get("/list", handler)          // /api/v2/list
v2.Get("/user", handler)          // /api/v2/user
Enter fullscreen mode Exit fullscreen mode

✅ WebSocket() method

Add WebSocket support using gorilla *Conn:

app := fiber.New()

app.WebSocket("/ws/:name", func(c *fiber.Conn) {
  log.Println(c.Params("name"))

  for {
    mt, msg, err := c.ReadMessage()
    if err != nil {
      log.Println("read:", err)
      break
    }

    log.Printf("recovery: %s", msg)

    err = c.WriteMessage(mt, msg)
    if err != nil {
      log.Println("write:", err)
      break
    }
  }
})

// ws://localhost:3000/ws/john
app.Listen(3000)
Enter fullscreen mode Exit fullscreen mode

✅ Recover() method

Recover from panic:

app.Get("/", func(c *fiber.Ctx) {
  panic("Something went wrong!") // it's panic time!
})

app.Recover(func(c *fiber.Ctx) {
  c.Status(500).Send(c.Error())
  // => 500 "Something went wrong!"
})
Enter fullscreen mode Exit fullscreen mode

✅ Map() method

Add shortcut for map[string]interface{}:

fiber.Map{
  "first_name": "John",
  "is_admin":   true,
}
Enter fullscreen mode Exit fullscreen mode

Go build

Updates & Improvements

And here are updates and improvements, that Fiber has prepared for you! 👇

ℹ️ Re-new HTTP methods

Add multiple middlewares/handlers inside routes & groups:

app.Get("/", middlewareOne(), middlewareTwo(), handler())
Enter fullscreen mode Exit fullscreen mode

🔀 Re-think Settings method

Pass optional settings before app initiation, inside New() method:

app := fiber.New(&fiber.Settings{
  Prefork:       true,
  CaseSensitive: true,
  StrictRouting: true,
  ServerHeader:  "Go Server",
  // ...other settings
})
Enter fullscreen mode Exit fullscreen mode

Deprecated & Removed list

Follow functions are deprecated and removed from Fiber v1.7:

🚫 app.Banner
🚫 ctx.BasicAuth
🚫 ctx.Json
🚫 ctx.JsonBytes
🚫 ctx.JsonString
🚫 ctx.Xml

🤖 Benchmarks

TechEmpower

TechEmpower

All results: https://www.techempower.com/benchmarks/#section=data-r19&hw=ph&test=composite&a=2

The Benchmarker

# Language Framework Speed (64) Speed (256) Speed (512) Speed (1024) Speed (2048)
6 go (1.13) fiber (1.7) 137902 147913 149225 143516 143006

All results: https://github.com/the-benchmarker/web-frameworks

💬 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, 1] Vic Shóstak https://github.com/koddr
[2, 3] 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 (8)

Collapse
 
lucafmarques profile image
Luca F. Marques • Edited

Is it advantageous to use a framework built on top of a custom HTTP stack (fasthttp) over other frameworks based on net/http for production?

The lack of HTTP/2 support and the, seemingly "hackish", implementation of WebSockets seem to outweigh the benefits to speed (read req/s).

Where and when should I use Fiber over something like Echo?

P.S.: The work on Fiber is great, hope to see it flourish in the future!

Collapse
 
fenny profile image
Fenny • Edited

Hi Luca, I'm one of the authors of Fiber and I will try to answer your questions.

  1. Why use fasthttp over net/http?
    The worker pool model is a zero allocation model, as the workers are already initialized and are ready to serve, whereas in the net/http implementation the go c.serve() has to allocate memory for the goroutine.
    The handler function definition signature is better, as it takes in only a context which includes both the request and writer needed by the handler.
    Overall fasthttp is a zero allocation model with a low memory footprint.

  2. Lack of HTTP/2 support
    Proxies/load-balancers like nginx, cloudflare ...etc take care of the HTTP/2 requests from the client browser. Most proxies do not support the HTTP/2 protocol from and to origin servers, since most web apps are behind a proxy/load-balancer this should not be a problem.

  3. "hackish", implementation of WebSockets
    I'm not sure what you mean with "hackish" but Fiber uses github.com/gorilla/websocket and this is a fast, well-tested and widely used WebSocket implementation for Go.

  4. Where and when should I use Fiber over something like Echo?
    If you need raw performance with a low memory footprint.
    If you ever worked with Expressjs (Fiber has a similair API).
    In the end it's up to you where you feel more comfortable

I hope I answered your questions, and if you have more feel free to ask!

Collapse
 
lucafmarques profile image
Luca F. Marques

Thanks for the awesome reply Fenny.

Hadn't thought about how proxies and load-balancers can help with the lack of HTTP/2 support.
The worker pool model is great, wonder why it couldn't be adopted by the standard lib, probably some lower level problem I'm not currently aware of.

As for Fiber, are you guys tackling documentation right now? I found the lack of a godoc page to slow my efforts in messing with the framework. Does the team need any help in this aspect?

Anyhow, thanks for the response and I wish the team good luck!

Thread Thread
 
fenny profile image
Fenny • Edited

No problem!

We have an extended online API documentation: fiber.wiki
I forgot to add some benchmark sources that might change your mind to use fiber versus other frameworks:

Plaintext
techempower.com/benchmarks/#sectio...
JSON serialization
techempower.com/benchmarks/#sectio...
Data updates
techempower.com/benchmarks/#sectio...

Collapse
 
pranjalagnihot8 profile image
Pranjal Agnihotri {..❤️}

I have experience in NodeJS and general JS stack for building web application. I want to learn Golang can someone please point out me to some good resources of GO ecosystem. I want to quickly cover basics topics and then jump into building backend with Golang.
I have experience with static languages like C++/Java/Typescript.
Thanks 🌸

Collapse
 
fenny profile image
Fenny

Hi Pranjal, these crash courses are a good start to learn the Go fundamentals:
youtube.com/watch?v=C8LgvuEBraI
youtube.com/watch?v=SqrbIlUwR0U
youtube.com/watch?v=YS4e4q9oBaU

Collapse
 
alphacodedev profile image
Minh Tran

Could you publish any Youtube Videos about Fiber, maybe making a REST AI with fiber, showing people the advantages of Fiber...

I am convinced that we got something big here and everyone should know about it.

Collapse
 
koddr profile image
Vic Shóstak

Thanks for idea 💡 we contacted some popular YouTube dev bloggers with this... and cross fingers 🤞