DEV Community

Cover image for 📖 Go Fiber by Examples: Working with middlewares and boilerplates
Vic Shóstak
Vic Shóstak

Posted on • Updated on

📖 Go Fiber by Examples: Working with middlewares and boilerplates

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 security & logging middlewares and useful boilerplates.

Yes, these are the main topics 👇

📝 Table of contents

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

Helmet middleware

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

// ./go/security_middlewares.go

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

// ...

// Use middlewares for each route
app.Use(
  helmet.New(), // add Helmet middleware
)
Enter fullscreen mode Exit fullscreen mode

↑ Table of contents

CSRF middleware

CSRF middleware for Fiber that provides 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/security_middlewares.go

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

// ...

// Use middlewares for each route
app.Use(
  csrf.New(), // add CSRF middleware
)
Enter fullscreen mode Exit fullscreen mode

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:

// 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
)
Enter fullscreen mode Exit fullscreen mode

↑ Table of contents

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/security_middlewares.go

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

// ...

// Use middlewares for each route
app.Use(
  limiter.New(), // add Limiter middleware
)
Enter fullscreen mode Exit fullscreen mode

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

// 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
)
Enter fullscreen mode Exit fullscreen mode

↑ Table of contents

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/logger_middlewares.go

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

// ...

// Use middlewares for each route
app.Use(
  logger.New(), // add Logger middleware
)
Enter fullscreen mode Exit fullscreen mode

And the console output looks like this:

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 
Enter fullscreen mode Exit fullscreen mode

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:

// 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
)
Enter fullscreen mode Exit fullscreen mode

↑ Table of contents

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

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 logo gofiber / boilerplate

🚧 Boilerplate for 🚀 Fiber

↑ Table of contents

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 logo create-go-app / cli

✨ A complete and self-contained solution for developers of any qualification to create a production-ready project with backend (Go), frontend (JavaScript, TypeScript) and deploy automation (Ansible, Docker) by running only one CLI command.

Create Go App

Create Go App CLI

Go version Go report Code coverage Wiki License

Create a new production-ready project with backend (Golang) frontend (JavaScript, TypeScript) and deploy automation (Ansible Docker) by running only one CLI command.

Focus on writing your code and thinking of the business-logic! The CLI will take care of the rest.

⚡️ Quick start

First, download and install Go. Version 1.20 or higher is required.

❗️ Note: If you're looking for the Create Go App CLI for other Go versions: 1.16, 1.17.

Installation is done by using the go install command:

go install github.com/create-go-app/cli/v4/cmd/cgapp@latest
Enter fullscreen mode Exit fullscreen mode

Or see the repository's Release page, if you want to download a ready-made deb, rpm, apk or Arch Linux package.

Also, GNU/Linux and macOS users available way to install via Homebrew:

# Tap a new formula:
brew tap create-go-app/tap

# Installation:
brew install create-go-app/tap/cgapp
Enter fullscreen mode Exit fullscreen mode

Let's create a new project via interactive console UI (or CUI

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 documentation and authorization of requests via JWT token.
  • The background part will be generated with Vite.js, 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 to deploy the application in isolated Docker containers on a remote server.

↑ Table of contents

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

Photos and videos by

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: 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: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
  • 🏃 yatr: 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: 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: 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: 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.

Top comments (7)

Collapse
 
yakar profile image
Aydın Yakar

Thanks for effort your time for articles 🙏✌️

Collapse
 
koddr profile image
Vic Shóstak

No problem! Have a nice read ;)

Collapse
 
xman profile image
Doan Vu

Thanks a lot for your articles. It helps me much in learning GoFiber to do my job.

Collapse
 
nigel447 profile image
nigel447

thanks for this, writing documentation is a pain at best, writing good documentation is an art form, this is high quality work and very much appreciated. much respect

Collapse
 
xiaoweil profile image
Xiaowei Liu

Great article, thank you for your time.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
koddr profile image
Vic Shóstak

I'm the person who wrote the Fiber documentation in the first place. So, I have every right to do so, check out the copyright on the Fiber website or the GitHub page, just for fun.

Hello, my name is Vic Shostak, I'm the one who created this framework.
Whats up, Aaron Kofi Gayi? May I now have your permission to reprint my own lines? :)

Especially since this is a chapter from my unreleased book (which I wrote about in the first article of this series), which I kindly decided to put out for FREE for everyone on this blogging service.

Question for you, Aaron: Why don't you write your own article that doesn't "reprint documentation"?

I just have never understood people who only criticize other people's work and offer nothing in return. This is called "toxicity" and only leads to degradation of our friendly community on Dev.to.

Please think about it. See you soon!