🚀 Fiber v1.8. What's new, updated and re-thinked?
Tags: go, node, news, fiber
Published: 2020-03-03 16:25:07

## 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](https://docs.gofiber.io/) 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](#ch-1)
  - [middleware.BasicAuth()](#ch-1-1)
  - [middleware.CORS()](#ch-1-2)
  - [middleware.Limiter()](#ch-1-3)
  - [middleware.Logger()](#ch-1-4)
  - [middleware.RequestID()](#ch-1-5)
  - [middleware.Helmet()](#ch-1-6)
- [New, Updated & Re-thinked](#ch-2)
  - [Range() method for Ctx](#ch-2-1)
  - [Compress() method for Ctx](#ch-2-2)
  - [Compression option for Settings](#ch-2-3)
  - [Immutable option for Settings](#ch-2-4)
- [Re-named list](#ch-3)
- [Do you like Fiber?](#ch-4)
- [Your assistance to project](#ch-5)

<a name="ch-1"></a>
## 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:

```bash
go get -u github.com/gofiber/fiber/...
```

And use it on `import` section (_after_ main package):

```go
// ...

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

// ...
```

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

<a name="ch-1-1"></a>
### ✅ middleware.BasicAuth()

Provides a very simple (but useful _sometimes_) authentication:

```go
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)
}
```

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

```bash
curl --user john:doe http://localhost:3000
```

<a name="ch-1-2"></a>
### ✅ middleware.CORS()

CORS _middleware_ implements [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) specification. It's _extremely_ useful middleware for work with frontend, when you build REST API.

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

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

    // ...
}
```

And now, run on console:

```bash
curl -H "Origin: http://example.com" --verbose http://localhost:3000
```

<a name="ch-1-3"></a>
### ✅ 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:

```go
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))

    // ...
}
```

<a name="ch-1-4"></a>
### ✅ middleware.Logger()

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

```go
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))

    // ...
}
```

<a name="ch-1-5"></a>
### ✅ middleware.RequestID()

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

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

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

    // ...
}
```

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

```bash
6ba7b810-9dad-11d1-80b4-00c04fd430c8
```

<a name="ch-1-6"></a>
### ✅ middleware.Helmet()

Helmet middleware provides protection against:

- Cross-Site Scripting (XSS) attack.
- Content type sniffing.
- Clickjacking.
- Insecure connection.
- And [other](https://github.com/gofiber/helmet) code injection attacks.

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

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

    // ...
}
```

![Fiber updates](https://dev-to-uploads.s3.amazonaws.com/i/rnx1kq5tcw1izjffh0du.jpg)

<a name="ch-2"></a>
## New, Updated & Re-thinked

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

<a name="ch-2-1"></a>
### ✅ Range() method for Ctx

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

```go
// 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]
    }
  }
})
```

<a name="ch-2-2"></a>
### ✅ Compress() method for Ctx

With this method you can easily _enable_/_disable_ compression within handlers.

```go
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
    })

    // ...
}
```

<a name="ch-2-3"></a>
### ℹ️ Compression option for Settings

Enables **GZip** or **Deflate** compression for all responses:

```go
app.Settings.Compression = true
```

<a name="ch-2-4"></a>
### ℹ️ Immutable option for Settings

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

```go
app.Settings.Immutable = true
```

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

<a name="ch-3"></a>
## Re-named list

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

<a name="ch-4"></a>
## 💬 Do you like Fiber? Tell about it!

Fiber authors are **always** listening to its users in [issues](https://github.com/gofiber/fiber/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](https://github.com/gofiber/fiber) 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?](https://dev-to-uploads.s3.amazonaws.com/i/v22vk8sjujiixm7i1jfg.jpg)

<a name="ch-5"></a>
## Your assistance to project 👍

1. Add a [GitHub Star](https://github.com/gofiber/fiber) to project.
2. Tweet about Fiber [on your Twitter](https://twitter.com/intent/tweet?text=%F0%9F%9A%80%20Fiber%20is%20an%20Express%20inspired%20web%20framework%20written%20in%20%23Go%20with%20%F0%9F%92%96%20https%3A%2F%2Fgithub.com%2Fgofiber%2Ffiber).
3. Help to translate `README` and [API Docs](https://docs.gofiber.io/) 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

<a name=""></a>
## P.S.

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

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 projects that need your help (and stars) 👇

- 🔥 [gowebly][gowebly_url]: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first CSS frameworks on the frontend.
- ✨ [create-go-app][cgapp_url]: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
- 🏃 [yatr][yatr_url]: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project.
- 📚 [gosl][gosl_url]: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.
- 🏄‍♂️ [csv2api][csv2api_url]: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API.
- 🚴 [json2csv][json2csv_url]: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size.

<!-- Footer links -->

[gowebly_url]: https://github.com/gowebly
[cgapp_url]: https://github.com/create-go-app
[yatr_url]: https://github.com/koddr/yatr
[gosl_url]: https://github.com/koddr/gosl
[csv2api_url]: https://github.com/koddr/csv2api
[json2csv_url]: https://github.com/koddr/json2csv