📖 Go Fiber by Examples: Working with middlewares and boilerplates
Tags: go, beginners, tutorial, showdev
Published: 2021-09-13 16:11:00

## Introduction

Hey, DEV friends! 👋 

So, we've already got a good understanding of the key features and the inner workings of the Fiber web framework. Now, it's the turn of additional tools and packages that can greatly improve our productivity as Go programmers.

## Plan for the Chapter 4

In this fourth article (or chapter), we will review the topics of the [Fiber](https://gofiber.io/) security & logging middlewares and useful boilerplates.

Yes, these are the main topics 👇

<a name="toc"></a>
### 📝 Table of contents

- [Working with Security middlewares](#working-with-security-middlewares)
  - [Helmet middleware](#helmet-middleware)
  - [CSRF middleware](#csrf-middleware)
  - [Limiter middleware](#limiter-middleware)
- [Explore Logging middleware](#explore-logging-middleware)
- [Useful Fiber Boilerplates](#useful-fiber-boilerplates)
- [Summary](#summary)

<a name="#working-with-security-middlewares"></a>
## Working with Security middlewares

Security middlewares in the Fiber web framework perform the task of protecting your application from various types of hacker attacks. This is **critical** for projects that work in production with real users. 

> ☝️ **Note:** However, even if you don't plan to put your project into production now, knowing about such middleware is still a useful skill.

[↑ Table of contents](#toc)

<a name="#helmet-middleware"></a>
### Helmet middleware

Helmet middleware helps to secure our Fiber application by setting various HTTP headers:

- [XSS Protection](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection)
- [Content-Type No Sniff](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options)
- [X-Frame Options](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options)
- [HSTS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security) Max Age
- [CSP Report Only](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only)
- Exclude Subdomains & Preload Enabled
- Content Security & Referrer Policies

```go
// ./go/security_middlewares.go

import "github.com/gofiber/helmet/v2"

// ...

// Use middlewares for each route
app.Use(
  helmet.New(), // add Helmet middleware
)
```

[↑ Table of contents](#toc)

<a name="#csrf-middleware"></a>
### CSRF middleware

CSRF middleware for Fiber that provides [Cross-Site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection by passing a CSRF token via cookies. 

This cookie value will be used to compare against the client CSRF token in the POST requests. When the CSRF token is invalid, this middleware will delete the `csrf_` cookie and return the `fiber.ErrForbidden` error.

```go
// ./go/security_middlewares.go

import "github.com/gofiber/fiber/v2/middleware/crsf"

// ...

// Use middlewares for each route
app.Use(
  csrf.New(), // add CSRF middleware
)
```

We can retrieve the CSRF token with `c.Locals(key)`, where key is the option name in the custom middleware configuration. 

The CSRF middleware custom config may look like this:

```go
// Set config for CSRF middleware
csrfConfig := csrf.Config{
  KeyLookup:      "header:X-Csrf-Token", // string in the form of '<source>:<key>' that is used to extract token from the request
  CookieName:     "my_csrf_",            // name of the session cookie
  CookieSameSite: "Strict",              // indicates if CSRF cookie is requested by SameSite
  Expiration:     3 * time.Hour,         // expiration is the duration before CSRF token will expire
  KeyGenerator:   utils.UUID,            // creates a new CSRF token
}

// Use middlewares for each route
app.Use(
  csrf.New(csrfConfig), // add CSRF middleware with config
)
```

[↑ Table of contents](#toc)

<a name="#limiter-middleware"></a>
### Limiter middleware

Limiter middleware for Fiber used to limit repeated requests to public APIs or endpoints such as password reset etc. Moreover, useful for API clients, web crawling, or other tasks that need to be throttled.

```go
// ./go/security_middlewares.go

import "github.com/gofiber/fiber/v2/middleware/limiter"

// ...

// Use middlewares for each route
app.Use(
  limiter.New(), // add Limiter middleware
)
```

Most of the time, you will probably be using this middleware along with your configuration. It's easy to add a config like this:

```go
// Set config for Limiter middleware
limiterConfig := limiter.Config{
  Next: func(c *fiber.Ctx) bool {
    return c.IP() == "127.0.0.1" // limit will apply to this IP
  },
  Max:        20,                // max count of connections
  Expiration: 30 * time.Second,  // expiration time of the limit
  Storage:    myCustomStorage{}, // used to store the state of the middleware
  KeyGenerator: func(c *fiber.Ctx) string {
    return c.Get("x-forwarded-for") // allows you to generate custom keys
  },
  LimitReached: func(c *fiber.Ctx) error {
    return c.SendFile("./too-fast-page.html") // called when a request hits the limit
  },
}

// Use middlewares for each route
app.Use(
  limiter.New(limiterConfig), // add Limiter middleware with config
)
```

[↑ Table of contents](#toc)

<a name="#explore-logging-middleware"></a>
## Explore Logging middleware

Like any other framework, Fiber also has its built-in middleware for logging HTTP request/response details and displaying results in the console. 

Let's look at an example of what this might look like:

```go
// ./go/logger_middlewares.go

import "github.com/gofiber/fiber/v2/middleware/logger"

// ...

// Use middlewares for each route
app.Use(
  logger.New(), // add Logger middleware
)
```

And the console output looks like this:

```console
08:17:42 | 404 |   85ms |  127.0.0.1 | GET   | /v1/user/123 
08:18:07 | 204 |  145ms |  127.0.0.1 | POST  | /v1/webhook/postmark 
08:19:53 | 201 |  138ms |  127.0.0.1 | PUT   | /v1/article/create 
```

Yes, Logger middleware connects in the same way as the middleware reviewed earlier. Furthermore, we can save all logs to a file, not console output, like this:

```go
// Define file to logs
file, err := os.OpenFile("./my_logs.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
  log.Fatalf("error opening file: %v", err)
}
defer file.Close()

// Set config for logger
loggerConfig := logger.Config{
  Output: file, // add file to save output
}

// Use middlewares for each route
app.Use(
  logger.New(loggerConfig), // add Logger middleware with config
)
```

[↑ Table of contents](#toc)

<a name="#useful-fiber-boilerplates"></a>
## Useful Fiber Boilerplates

Fiber has already gathered a friendly community of programmers from all over the world. Every day, they share new and interesting packages and templates, which make starting a new project easier for us.

Boilerplate projects not only allow you to create a complete application structure with all the settings, but also a better understanding of the principle of code organization in the ecosystem of the web framework on a real example.

Here we will only look at two of the most popular examples from the large number of such projects used by Fiber community and authors. But we can always find and use others, or even create our own and offer them to the community!

[↑ Table of contents](#toc)

<a name="#the-official-boilerplate-application-template"></a>
### The official boilerplate application template

This template was specially created by the authors of Fiber for a quick enter to the framework, without additional third-party packages. The application is specially designed to run in the Docker container.

{% github gofiber/boilerplate no-readme %}

[↑ Table of contents](#toc)

<a name="#the-create-go-app-project"></a>
### The Create Go App project

When talking about boilerplate packages, I can't help but mention a project that has already helped many developers (myself included) to create new Go projects in a matter of minutes.

{% github create-go-app/cli %}

The project is a handy interactive CLI with which you can easily create a full-fledged web application in just a couple of clicks: 

- Out of the box, the project has its own fully configured Fiber REST API application template with automatic [Swagger](https://swagger.io/) documentation and authorization of requests via [JWT token](https://jwt.io/).
- The background part will be generated with [Vite.js](https://vitejs.dev/), and you are free to choose absolutely any startup template for React, Preact, Vue, Svelte, web components, vanilla JavaScript or TypeScript and so on.
- Specifically configured roles and playbooks for the [Ansible](https://www.ansible.com/) to deploy the application in isolated [Docker containers](https://www.docker.com/) on a remote server.
 
{% youtube 5-DNZFU9TOQ %}

[↑ Table of contents](#toc)

<a name="#summary"></a>
## Summary

Wow, here's a summary of the chapter you passed! We learned how easy it is to make our Fiber application secure by adding some built-in middlewares. 

Then there was a detailed breakdown of how the logging system works, which will help us more than once in future articles in this series.

Next time, we'll learn even more about utility middlewares, external Fiber middlewares and the third-party packages for this wonderful web framework. 

Stay tuned, don't switch! 😉

[↑ Table of contents](#toc)

<a name=""></a>
## Photos and videos by

- Kolya Korzh https://unsplash.com/photos/UOq-FqdlTpw

<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