跳转到主要内容

标签(标签)

资源精选(342) Go开发(108) Go语言(103) Go(99) angular(82) LLM(75) 大语言模型(63) 人工智能(53) 前端开发(50) LangChain(43) golang(43) 机器学习(39) Go工程师(38) Go程序员(38) Go开发者(36) React(33) Go基础(29) Python(24) Vue(22) Web开发(20) Web技术(19) 精选资源(19) 深度学习(19) Java(18) ChatGTP(17) Cookie(16) android(16) 前端框架(13) JavaScript(13) Next.js(12) 安卓(11) 聊天机器人(10) typescript(10) 资料精选(10) NLP(10) 第三方Cookie(9) Redwoodjs(9) LLMOps(9) Go语言中级开发(9) 自然语言处理(9) PostgreSQL(9) 区块链(9) mlops(9) 安全(9) 全栈开发(8) ChatGPT(8) OpenAI(8) Linux(8) AI(8) GraphQL(8) iOS(8) 软件架构(7) Go语言高级开发(7) AWS(7) C++(7) 数据科学(7) whisper(6) Prisma(6) 隐私保护(6) RAG(6) JSON(6) DevOps(6) 数据可视化(6) wasm(6) 计算机视觉(6) 算法(6) Rust(6) 微服务(6) 隐私沙盒(5) FedCM(5) 语音识别(5) Angular开发(5) 快速应用开发(5) 提示工程(5) Agent(5) LLaMA(5) 低代码开发(5) Go测试(5) gorm(5) REST API(5) 推荐系统(5) WebAssembly(5) GameDev(5) CMS(5) CSS(5) machine-learning(5) 机器人(5) 游戏开发(5) Blockchain(5) Web安全(5) Kotlin(5) 低代码平台(5) 机器学习资源(5) Go资源(5) Nodejs(5) PHP(5) Swift(5) 智能体(4) devin(4) Blitz(4) javascript框架(4) Redwood(4) GDPR(4) 生成式人工智能(4) Angular16(4) Alpaca(4) 编程语言(4) SAML(4) JWT(4) JSON处理(4) Go并发(4) kafka(4) 移动开发(4) 移动应用(4) security(4) 隐私(4) spring-boot(4) 物联网(4) nextjs(4) 网络安全(4) API(4) Ruby(4) 信息安全(4) flutter(4) 专家智能体(3) Chrome(3) CHIPS(3) 3PC(3) SSE(3) 人工智能软件工程师(3) LLM Agent(3) Remix(3) Ubuntu(3) GPT4All(3) 软件开发(3) 问答系统(3) 开发工具(3) 最佳实践(3) RxJS(3) SSR(3) Node.js(3) Dolly(3) 移动应用开发(3) 低代码(3) IAM(3) Web框架(3) CORS(3) 基准测试(3) Go语言数据库开发(3) Oauth2(3) 并发(3) 主题(3) Theme(3) earth(3) nginx(3) 软件工程(3) azure(3) keycloak(3) 生产力工具(3) gpt3(3) 工作流(3) C(3) jupyter(3) 认证(3) prometheus(3) GAN(3) Spring(3) 逆向工程(3) 应用安全(3) Docker(3) Django(3) R(3) .NET(3) 大数据(3) Hacking(3) 渗透测试(3) C++资源(3) Mac(3) 微信小程序(3) Python资源(3) JHipster(3) 大型语言模型(2) 语言模型(2) 可穿戴设备(2) JDK(2) SQL(2) Apache(2) Hashicorp Vault(2) Spring Cloud Vault(2) Go语言Web开发(2) Go测试工程师(2) WebSocket(2) 容器化(2) AES(2) 加密(2) 输入验证(2) ORM(2) Fiber(2) Postgres(2) Gorilla Mux(2) Go数据库开发(2) 模块(2) 泛型(2) 指针(2) HTTP(2) PostgreSQL开发(2) Vault(2) K8s(2) Spring boot(2) R语言(2) 深度学习资源(2) 半监督学习(2) semi-supervised-learning(2) architecture(2) 普罗米修斯(2) 嵌入模型(2) productivity(2) 编码(2) Qt(2) 前端(2) Rust语言(2) NeRF(2) 神经辐射场(2) 元宇宙(2) CPP(2) 数据分析(2) spark(2) 流处理(2) Ionic(2) 人体姿势估计(2) human-pose-estimation(2) 视频处理(2) deep-learning(2) kotlin语言(2) kotlin开发(2) burp(2) Chatbot(2) npm(2) quantum(2) OCR(2) 游戏(2) game(2) 内容管理系统(2) MySQL(2) python-books(2) pentest(2) opengl(2) IDE(2) 漏洞赏金(2) Web(2) 知识图谱(2) PyTorch(2) 数据库(2) reverse-engineering(2) 数据工程(2) swift开发(2) rest(2) robotics(2) ios-animation(2) 知识蒸馏(2) 安卓开发(2) nestjs(2) solidity(2) 爬虫(2) 面试(2) 容器(2) C++精选(2) 人工智能资源(2) Machine Learning(2) 备忘单(2) 编程书籍(2) angular资源(2) 速查表(2) cheatsheets(2) SecOps(2) mlops资源(2) R资源(2) DDD(2) 架构设计模式(2) 量化(2) Hacking资源(2) 强化学习(2) flask(2) 设计(2) 性能(2) Sysadmin(2) 系统管理员(2) Java资源(2) 机器学习精选(2) android资源(2) android-UI(2) Mac资源(2) iOS资源(2) Vue资源(2) flutter资源(2) JavaScript精选(2) JavaScript资源(2) Rust开发(2) deeplearning(2) RAD(2)

Introduction

Hello and welcome, DEV friends! 👋

As you probably know, the printed book that we planned to release with Packt publisher called Easy Development with GoFiber is now canceled.

🤯 There are many reasons for this, both from my side and from the side of this respected publisher, I will not focus on this.

Therefore, I decided to release all of my written material in free access as a series of articles in my blog on Dev.to for everyone! 😉

Today, I start a new series of articles called Go Fiber by Examples, which will be a handbook for those who want to learn the Fiber web framework quickly and efficiently while developing a real web application.

Plan for the Chapter 1

In this first article (or chapter), we will take a look at the history of the Fiber web framework, find out which groups of programmers are best suited to it, and see how similar it is to Node.js framework Express, using real-world examples.

We are going to cover the following main topics 👇

📝 Table of contents

Coming from another programming language or Golang web framework

If you come from another language (such as PythonRuby, or JavaScript), the Fiber web framework will help you to smoothly enter into the Go programming language.

It has very familiar elements and is designed to make the product development process as easy as possible for developers of different skill levels from other programming languages.

For developers who are already working with other Go web frameworks or API tools, Fiber can offer the following benefits:

  • Extreme performance and low memory footprint
  • Rapid server-side programming
  • Built-in middleware for most tasks
  • Rich and robust routing
  • Easy serve static files and work with databases
  • Support of all popular template engines
  • ...and much, much more to talk about in this series!

A friendly and supportive Fiber community around the World has already translated basic documentation into 15 different languages and is ready to support you in issues of the project repository on GitHub.

↑ Table of contents

Looking to swap NodeJS for Go

New gophers that make the switch from Node.js to Golang are dealing with a learning curve before they can start building their web applications, APIs, or microservices.

Fiber inspired by Express, the most popular web framework on the Internet. Its authors combined the ease of Express and the raw performance of Go.

And we will be surprised at how easy it is to make the transition from one language to a wholly different one, thanks to learning just the Fiber Web Framework!

🌐 Note: Also, I recommend visiting the GitHub repository by Miguel Mota called Golang for Node.js Developers. It describes the basic principles for a smoother transition of your backend from JavaScript to Go in a fairly straightforward way.

Therefore, if you have ever implemented a web application in Node.js (using Express or similar), then many methods and principles will seem very common to you.

We will discuss this in more detail near the end of this article.

↑ Table of contents

The philosophy behind using Fiber web framework

Fiber, as a web framework, was created with the idea of minimalism and follows the UNIX way, so that new gophers can quickly enter the world of Go with a warm and trusted welcome. That’s why Fiber is a very versatile Go framework.

But the main focus of its application is to create complete all-in-one web applications, like Django in Python or Ruby on Rails in Ruby, and efficient high-performance REST APIs, like FastAPI for Python.

This does not mean that you cannot create microservices or adapters for your infrastructure or even desktop network apps or else on Fiber. Absolutely no! Such areas are simply not a priority for the authors of this framework. But they always listen to its users in issues on GitHub repository, Discord channel, and all over the Internet.

The authors want to create a fast, flexible, and friendly Golang web framework for any task, deadline, and developer skill. Just like Express framework does in the JavaScript world.

↑ Table of contents

A brief comparison with Express

Being inspired by Express, the Fiber web framework may seem very familiar to you. We will break down the most basic things in the next sections, where you can see them for yourself.

👌 Note: Don't worry if you have never worked with Go or JavaScript, we have left comprehensive comments in the code examples below to help you get oriented.

Hello World

A classic example for every programming language or web framework is the minimally working Hello World program. Well, let's not deny ourselves that!

First, let's take a look at Express:

// ./js/hello_world.js

const express = require("express"); // add Express library
const app = express(); // create a new Express instance

// Create a new endpoint
app.get("/", (req, res) => {
  res.send("Hello World!"); // send text
});

// Start server on port 3000
app.listen(3000);

Straightforward, isn't it? Just a couple of lines of code and a full-fledged web server is ready to receive users on the specified endpoint on port 3000.

And here's how the same functionality can be implemented with Fiber:

// ./go/hello_world.go

package main

import "github.com/gofiber/fiber/v2" // add Fiber package

func main() {
  app := fiber.New() // create a new Fiber instance

  // Create a new endpoint
  app.Get("/", func(c *fiber.Ctx) error {
    return c.SendString("Hello, World!") // send text
  })

  // Start server on port 3000
  app.Listen(":3000")
}

Except for some JavaScript or Go-specific blocks at the beginning of the program, the code reads, feels, and works the same under the hood. And this state will follow us in almost all the code examples in this series.

↑ Table of contents

Basic routing and endpoints

As you know, any web application, microservice, or API includes a routing system based on endpoints describing an HTTP method and a handler function, which will be executed only after this endpoint receives a request from the client-side.

In the preceding Hello World program, we already touched the app.get(path, () => {}) (in case of Express) and app.Get(path, func() error {}) (in case of Fiber) endpoints, which serve the HTTP GET method and return a plain string when requested.

Let’s take a look at the other HTTP methods which we can use to describe the endpoint in our web application. Let's start, per tradition, with the Express:

// ./js/routing.js

// Endpoint for POST method
app.post("/", (req, res) => {
  // function that stores a new data
});

// Endpoint for PUT method
app.put("/", (req, res) => {
  // function that replaces the existing data
});

// Endpoint for PATCH method
app.patch("/", (req, res) => {
  // function that replaces part of the existing data
});

// Endpoint for DELETE method
app.delete("/", (req, res) => {
  // function that deletes the data
});

It might seem that these HTTP methods are not enough to describe the endpoints of your web application, but in fact, Express, and Fiber support many more request HTTP methods.

☝️ Note: We have only described the most basic ones!

Now let's take a look at how the same basic HTTP methods look in Fiber:

// ./go/routing.go

// Endpoint for Post method
app.Post("/", func(c *fiber.Ctx) error {
  // function that stores a new data
})

// Endpoint for PUT method
app.Put("/", func(c *fiber.Ctx) error {
  // function that replaces the existing data
})

// Endpoint for PATCH method
app.Patch("/", func(c *fiber.Ctx) error {
  // function that replaces part of the existing data
})

// Endpoint for DELETE method
app.Delete("/", func(c *fiber.Ctx) error {
  // function that deletes the data
})

Again, except for some blocks specific to each programming language, the code reads and works the same.

↑ Table of contents

Using middleware

The middleware functions have access to the HTTP request and response objects and the next middleware function. They can perform the following tasks:

  • Execute any code we need
  • Make any changes and modifications to the request and response objects
  • Complete the request-response loop
  • Call the next middleware function that is in the stack

We are not going to delve into middleware now. Our goal is only to compare the technical design of these web frameworks.

👌 Note: We will return to middleware in later articles of this series.

So, here is an example of a middleware function for the Express framework that outputs the current date and time to the browser console and simply passes the request to the next endpoint:

// ./js/middleware.js

// Middleware function
app.use(function (req, res, next) {
  // print current date and time to console
  console.log("Date:", Date.now());

  // passing the request to the next endpoint
  next();
});

And this is how the same middleware will work with Fiber, but the date and time will be output to the normal terminal instead of the browser console:

// ./go/middleware.go

// Middleware function
app.Use(func(c *fiber.Ctx) error {
  // print current date and time to console
  fmt.Println("Date:", time.Now())

  // passing the request to the next endpoint
  return c.Next()
})

Once again, we saw similarities between these web frameworks.

↑ Table of contents

Serving static files

If we want to create a Single-Page Application rather than an ordinary web application, we will need to be able to request a directory with static files.

These files are usually:

  • Images
  • CSS files
  • JavaScript files
  • HTML files
  • Template and other downloadable files

The process of working with them is based on this scheme:

  1. Define a folder to store static files.
  2. Specify it as a mount point in the web application.
  3. In the HTML file (or template) we make references to this mount point.

Let's look at a small example to get an understanding.

If we store statics in the ./public folder at the root of our directory, then using the Express built-in express.static() function, we can mount it at /static address as follows:

// ./js/static.js

app.use(
  "/static", // mount address
  express.static("public") // path to the file folder
);

And here's a sample code for Fiber that will do the same thing for us:

// ./go/static.go

app.Static(
  "/static",  // mount address
  "./public", // path to the file folder
)

As a result, all static files for both Express and Fiber will be available at the following address:

http://localhost:3000/static/images/background.jpg 
http://localhost:3000/static/css/style.css 
http://localhost:3000/static/js/app.js 
http://localhost:3000/static/index.html

With this approach, we can easily set up a proxy server, such as NGINX, to send static files more efficiently.

↑ Table of contents

Working with templates

When we build a web application that not only has to return content in JSON format but also has to be able to render templates with that content, template engines come to the rescue.

Both web frameworks support a huge number of template engines right out of the box: PugJadeMustacheHandlebars, and many others. Let's take a look at the Pug engine to see how a template renders in Express works:

// ./js/templates.js

// Initialize Pug template engine for rendering
app.set("view engine", "pug");

// Initialize templates folder
app.set("views", "./views");

// Create a new endpoint
app.get("/", (req, res) => {
  // rendering the "index" template with content passing
  res.render("index", {
    title: "Hey!",
    message: "This is the index template.",
  });
});

For Fiber, the same example will be a little more complicated but will remain just as familiar. The reason for this is that the configuration of the application cannot be changed after the Fiber instance has been created. It is read-only.

// ./go/templates.go

// Initialize Pug template engine in ./views folder
engine := pug.New("./views", ".pug")

// Create a new Fiber instance
app := fiber.New(fiber.Config{
  Views: engine, // set template engine for rendering
})

// Create a new endpoint
app.Get("/", func(c *fiber.Ctx) error {
  // rendering the "index" template with content passing
  return c.Render("index", fiber.Map{
    "Title":   "Hey!",
    "Message": "This is the index template.",
  })
})

⚙️ Note: Both frameworks will only look for templates with *.pug extension in the ./views folder of the current directory. If this folder does not exist or does not contain a file named index.pug, an error will happen.

Even though Express and Fiber written in different programming languages and by different development teams, they have a very similar technical design of built-in functions and working principles. This is what makes Fiber so special among many Go-based web frameworks.

We will explain this in more detail later in the future articles.

↑ Table of contents

Summary

We hope this article of the series has shown you a different side of the Go language, if you've only ever written code for your web applications in JavaScript before.

Furthermore, we do numerous new things:

  • We learned what Fiber is good for and where it can be used effectively.
  • We compared the basic functions of the Express and Fiber web frameworks.
  • Dismantled the routing system of web frameworks using simple examples.
  • Understood what middleware is and how to work with it in Fiber.
  • We looked at an example of how Fiber works with static files.
  • We found out what popular template engines Fiber supports out of the box and how to work with them.

In the next articles, we will get even closer to the inner workings of the Fiber web framework, its built-in components and methods.

标签