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.
Helmet middleware
Helmet middleware helps to secure our Fiber application by setting various HTTP headers:
- XSS Protection
- Content-Type No Sniff
- X-Frame Options
- HSTS Max Age
- CSP Report Only
- Exclude Subdomains & Preload Enabled
- Content Security & Referrer Policies
// ./go/security_middlewares.go
import "github.com/gofiber/helmet/v2"
// ...
// Use middlewares for each route
app.Use(
helmet.New(), // add Helmet middleware
)
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
)
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
)
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
)
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
)
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
)
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
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
)
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!
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.
gofiber / boilerplate
🚧 Boilerplate for 🚀 Fiber
The Gowebly project
A next-generation CLI tool that makes it easy to create amazing web applications with Go on the backend (included Fiber), using htmx, hyperscript or Alpine.js, and the most popular CSS frameworks on the frontend.
Main features:
- 100% free and open source under the Apache 2.0 license.
- For any developer's level of knowledge and technical expertise, as the intelligent CLI does most of the routine project setup for you, creates an understandable structure, and prepares code for use and deployment in production.
- Cross-platform and multi-architecture allows successful running on any GNU/Linux distros, Microsoft Windows (including WSL) and Apple macOS.
- Well-documented, includes translations in many other languages (Русский, 简体中文, Español).
- Enables you to start a new project faster with Go, htmx, hyperscript or Alpine.js libraries.
- Supports the built-in net/http package and the most popular Go web frameworks and routers out of the box, such as Fiber, Gin, Echo, Chi, HttpRouter, Gorilla/Mux and PocketBase.
- Supports the most popular CSS frameworks out of the box, such as Tailwind CSS, daisyUI, Flowbite, Preline UI, UnoCSS, Bootstrap and Bulma.
- Supports a new JavaScript runtime environment called Bun for the frontend.
- Supports a way to build HTML with Go using the Templ package.
- Supports a live-reload mode for your Go code and frontend files using Air tool.
- Includes a basic config for golangci-lint for quick setup.
- Ready-to-use Dockerfile and Docker Compose files to deploy your application in any environment.
- Ready-to-install as PWA (Progressive Web App) in your browser or mobile device.
- Has a library of user-friendly helpers for your Go code.
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.
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.
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.
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! 😉
Photos and videos by
- Kolya Korzh https://unsplash.com/photos/UOq-FqdlTpw
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.
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.
Top comments (8)
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
Great article, thank you for your time.
Hi Vic!
Thanks for Fiber and for this articles! Just waiting for the next one.
Thanks a lot for your articles. It helps me much in learning GoFiber to do my job.
Thanks for effort your time for articles 🙏✌️
No problem! Have a nice read ;)
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.
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!