新聞中心
大家好,我是 polarisxu。

創(chuàng)新互聯(lián)公司專(zhuān)注于肅南裕固族自治企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,成都商城網(wǎng)站開(kāi)發(fā)。肅南裕固族自治網(wǎng)站建設(shè)公司,為肅南裕固族自治等地區(qū)提供建站服務(wù)。全流程按需設(shè)計(jì)網(wǎng)站,專(zhuān)業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)公司專(zhuān)業(yè)和態(tài)度為您提供的服務(wù)
每次發(fā)框架相關(guān)的文章,總有人提到 Go Fiber 框架。于是乎,學(xué)習(xí)了下 Fiber,感覺(jué)確實(shí)挺不錯(cuò)的。因此寫(xiě)下這個(gè) Fiber 系列。
Fiber 項(xiàng)目地址:https://github.com/gofiber/fiber,目前 Star 數(shù) 15.3k+。
01 Fiber 框架
這是一個(gè) Go 語(yǔ)言 Web 框架,啟發(fā)自 NodeJS 框架:Express。該框架基于 FastHTTP 構(gòu)建,旨在簡(jiǎn)化、零內(nèi)存分配和提高性能,以便快速開(kāi)發(fā)。
如果你是一位 NodeJS 開(kāi)發(fā)者,想學(xué)習(xí) Go,這個(gè)框架應(yīng)該很適合你,同時(shí)這里還有一份專(zhuān)門(mén)為 NodeJS 開(kāi)發(fā)者準(zhǔn)備的 Go 學(xué)習(xí)資料:https://github.com/miguelmota/golang-for-nodejs-developers
這個(gè)框架是 2020 年 1 月份啟動(dòng)開(kāi)發(fā)的,沒(méi)想到短時(shí)間就受到很多人關(guān)注。從 README 的多國(guó)語(yǔ)言就可見(jiàn)一斑:
從第三方性能測(cè)試結(jié)果看,F(xiàn)iber 的表現(xiàn)比 Gin、Echo 好很多。這里有詳細(xì)的 Benchmark 測(cè)試說(shuō)明:https://docs.gofiber.io/extra/benchmarks。
摘抄一段官方關(guān)于 Fiber 的哲學(xué):
Fiber 作為一個(gè) Web 框架 ,是按照極簡(jiǎn)主義的思想并遵循 UNIX 方式創(chuàng)建的,因此新的 gopher 可以在熱烈和可信賴(lài)的歡迎中迅速進(jìn)入 Go 的世界。
Fiber 受到了互聯(lián)網(wǎng)上最流行的 Web 框架 Express 的啟發(fā) 。我們結(jié)合了 Express 的易用性和 Go 的原始性能 。如果您曾經(jīng)在 Node.js 上實(shí)現(xiàn)過(guò) Web 應(yīng)用程序(使用 Express 或類(lèi)似工具),那么許多方法和原理對(duì)您來(lái)說(shuō)應(yīng)該非常易懂。
我們關(guān)注 整個(gè)互聯(lián)網(wǎng) 用戶(hù)在 issues 和 Discord channel 的消息,為了創(chuàng)建一個(gè)迅速,靈活以及友好的 Go Web 框架,滿(mǎn)足任何任務(wù),最后期限和開(kāi)發(fā)者技能。就像 Express 在 JavaScript 世界中一樣。
所以,總結(jié)一下 Fiber 的特點(diǎn)(優(yōu)勢(shì)):
- 強(qiáng)大的路由
- 靜態(tài)文件服務(wù)
- 極致高性能
- 內(nèi)存占用低
- API 接口
- 中間件和 Next 支持
- 快速服務(wù)器端編程
- 支持各種模版引擎
- WebSocket 支持
- 頻率限制器
- 文檔被翻譯為 16 種語(yǔ)言
不過(guò)有兩點(diǎn)需要注意,F(xiàn)iber 使用了 unsafe 和 fasthttp,所以可能和 Go 最新版本有兼容性問(wèn)題。目前 Fiber 2.18.0 兼容 Go 1.14 到 Go1.17;但 fasthttp 和 net/http 是不兼容的,因此 net/http 生態(tài)的項(xiàng)目無(wú)法使用在 fiber 上。
02 和 Express 的簡(jiǎn)短比較
既然是受 Express 啟發(fā),那就和它比較下。
Hello World
基于 Express 的 Hello World 程序:
- const express = require("express"); // 引用 Express library
- const app = express(); // 創(chuàng)建一個(gè) Express 實(shí)例
- // 路由:/ endpoint
- app.get("/", (req, res) => {
- res.send("Hello World!");
- });
- // 在 3000 端口啟動(dòng)服務(wù)
- app.listen(3000);
確實(shí)挺簡(jiǎn)單,幾行代碼就搞定了一個(gè) Web 服務(wù)。
現(xiàn)在用 Fiber 實(shí)現(xiàn)類(lèi)似上面的功能:
- package main
- import "github.com/gofiber/fiber/v2" // 注意,最新版本是 v2.18.0,所以有 v2
- func main() {
- app := fiber.New() // 創(chuàng)建一個(gè) Fiber 實(shí)例
- // 路由:/ endpoint
- app.Get("/", func(c *fiber.Ctx) error {
- return c.SendString("Hello, World!")
- })
- // 在 3000 端口啟動(dòng)服務(wù)
- app.Listen(":3000")
- }
目前,幾乎所有 Go 框架都是類(lèi)似的路子,沒(méi)有太多好解釋的。
Fiber 啟動(dòng)后終端的輸出結(jié)果:
- $ go run main.go
- ┌───────────────────────────────────────────────────┐
- │ Fiber v2.18.0 │
- │ http://127.0.0.1:3000 │
- │ (bound on host 0.0.0.0 and port 3000) │
- │ │
- │ Handlers ............. 2 Processes ........... 1 │
- │ Prefork ....... Disabled PID ............. 83538 │
- └───────────────────────────────────────────────────┘
路由和端點(diǎn)
任何 Web 應(yīng)用程序、微服務(wù)或 API 都包含一個(gè)基于描述 HTTP 方法的端點(diǎn)(endpoint)和處理程序函數(shù)的路由系統(tǒng),只有在這個(gè)端點(diǎn)接收到客戶(hù)端的請(qǐng)求后才會(huì)執(zhí)行這個(gè)路由系統(tǒng)。
除了上面的 HTTP GET 方法,Express 和 Fiber 還支持其他 HTTP 基本方法(當(dāng)然還支持其他 HTTP 方法)。
- // 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
- });
對(duì)應(yīng)的 Fiber 代碼:
- // 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 PATH method
- app.Path("/", 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
- })
中間件
中間件函數(shù)可以訪(fǎng)問(wèn) HTTP 請(qǐng)求和響應(yīng)對(duì)象,以及調(diào)用下一個(gè)中間件函數(shù)。一般地,中間件函數(shù)執(zhí)行如下動(dòng)作:
- 執(zhí)行我們想讓其執(zhí)行的代碼
- 對(duì)請(qǐng)求或響應(yīng)對(duì)象做任何修改
- 完成請(qǐng)求-響應(yīng)循環(huán)
- 調(diào)用堆棧中的下一個(gè)中間件函數(shù)
看一個(gè)中間件的例子,它們?cè)?Express 和 Fiber 中如何寫(xiě)。
- app.use(function (req, res, next) {
- // 打印當(dāng)前時(shí)間
- console.log("Date:", Date.now());
- next();
- });
對(duì)應(yīng) Fiber 的代碼如下:
- app.Use(func(c *fiber.Ctx) error {
- // 打印當(dāng)前時(shí)間
- fmt.Println("Date:", time.Now())
- return c.Next()
- })
服務(wù)靜態(tài)文件
Web 應(yīng)用經(jīng)常會(huì)有靜態(tài)文件,它們需要能夠被請(qǐng)求,比如圖片、css/js 文件等。
服務(wù)靜態(tài)文件,一般基于如下幾個(gè)點(diǎn):
- 一個(gè)存儲(chǔ)靜態(tài)文件的文件夾
- 在 Web 程序中指定掛載點(diǎn)
- 對(duì)掛載點(diǎn)進(jìn)行引用
看看 Express 如何做到的:
- app.use(
- "/static", // mount address
- express.static("public") // path to the file folder
- );
對(duì)應(yīng) Fiber 的代碼如下:
- app.Static(
- "/static", // mount address
- "./public", // path to the file folder
- )
因此,我們對(duì) /static/ 下的文件訪(fǎng)問(wèn),都對(duì)應(yīng)到 public 下的文件。比如:
http://localhost:3000/static/images/background.jpg 對(duì)應(yīng)是 public/images/background.jpg 文件
使用模板
目前,Go 很多框架對(duì)各種模板引擎支持是不夠的。但 Fiber 做到了和 Express 類(lèi)似,支持大量開(kāi)箱即用的模板引擎,比如:Pug、Jade、Mustache 和 Handlebars 等。
以 Pug 為例,看看 Express 和 Fiber 如何使用的。(注意,以下代碼會(huì)查找 ./views 目錄下的 index.pug 文件,沒(méi)有該文件會(huì)報(bào)錯(cuò))
- app.set("view engine", "pug");
- // 初始化模板文件夾
- app.set("views", "./views");
- app.get("/", (req, res) => {
- res.render("index", {
- title: "Hey!",
- message: "This is the index template.",
- });
- });
對(duì)應(yīng)的 Fiber 代碼如下(注意,F(xiàn)iber 對(duì)模板的支持是 https://github.com/gofiber/template 包):
- // 基于 ./views 文件夾初始化 Pug 模板引擎
- engine := pug.New("./views", ".pug")
- app := fiber.New(fiber.Config{
- Views: engine, // 設(shè)置模板引擎
- })
- app.Get("/", func(c *fiber.Ctx) error {
- return c.Render("index", fiber.Map{
- "Title": "Hey!",
- "Message": "This is the index template.",
- })
- })
03 小結(jié)
本文簡(jiǎn)單介紹了 Fiber 的一些特性。因?yàn)?Fiber 是受 Express 啟發(fā)實(shí)現(xiàn)的,因此和 Express 進(jìn)行了對(duì)比。不知道你對(duì) Fiber 有什么感覺(jué)?
下篇文章會(huì)較詳細(xì)的介紹 Fiber 的一些特性。
參考
https://dev.to/koddr/go-fiber-by-examples-how-can-the-fiber-web-framework-be-useful-487a
本文轉(zhuǎn)載自微信公眾號(hào)「polarisxu」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系polarisxu公眾號(hào)。
https://docs.gofiber.io/api/fiber
分享文章:GoFiber框架系列之一:和Express對(duì)比學(xué)習(xí)
網(wǎng)頁(yè)鏈接:http://www.fisionsoft.com.cn/article/cojocoi.html


咨詢(xún)
建站咨詢(xún)
