Go Web框架 Fiber

image.png

一个用Go语言编写的受Express启发的Web框架。

Fiber是一个基于Fasthttp(Go最快的HTTP引擎)构建的Go Web框架。它旨在简化零内存分配性能的情况,以便快速开发。

package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
)

func main() {
    app := fiber.New()

    app.Get("/", func (c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    log.Fatal(app.Listen(":3000"))
}

强大的路由

为您的应用程序设置路由从未如此简单!类似Express的路线定义易于理解和使用。

app.Get("/", func (c *fiber.Ctx) error {
    return c.SendString("GET request")
})

app.Get("/:param", func (c *fiber.Ctx) error {
    return c.SendString("param: " + c.Params("param"))
})

app.Post("/", func (c *fiber.Ctx) error {
    return c.SendString("POST request")
})

服务静态文件

通过定义静态路由轻松地为您的静态HTML,CSS和JavaScript文件提供服务。您也可以在同一路径上提供多个目录的内容!

app.Static("/", "./public")

// => http://localhost:3000/hello.html
// => http://localhost:3000/js/jquery.js
// => http://localhost:3000/css/style.css

// serve from multiple directories
app.Static("/", "./files")

极限表现

由于Fiber建立在Fasthttp之上,因此您的应用程序将享受无与伦比的性能!

基准图

支持API

Fiber是在Go中构建REST API的理想选择。接收和发送数据既快速又简单!

app.Get("/api/posts", func (c *fiber.Ctx) error {
    posts := getPosts() // your logic
    if len(posts) == 0 {
        return c.Status(404).JSON(&fiber.Map{
            "success": false,
            "error":   "There are no posts!",
        })
    }
    return c.JSON(&fiber.Map{
        "success": true,
        "posts":   posts,
    })
})

灵活的中间件支持

许多现有的中间件中进行选择,或者创建自己的中间件!在它们到达您的控制器之前,可以使用它们来验证和处理您应用中的某些请求。

package main

import (
    "log"
    
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/cors"
)

func main() {
    app := fiber.New()

    app.Use(cors.New())

    app.Use(func (c *fiber.Ctx) error {
        if c.Is("json") {
            return c.Next()
        }
        return c.SendString("Only JSON allowed!")
    })

    app.Get("/", func(c *fiber.Ctx) error {
        return c.JSON(fiber.Map{
            "message": "Hello World",
        })
    })

    log.Fatal(app.Listen(":3000"))
}

低内存占用

Fiber的低内存占用量使您能够实现功能,而不必担心应用程序将使用多少内存。这使您可以专注于应用程序及其业务逻辑,而不是技术细节。

模板引擎

是否要在Fiber应用程序中使用其他模板引擎?别再害怕了!由于使用了模板中间件,Fiber支持多个模板引擎,例如Handlebars和Pug 。

package main

import (
    "log"

    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/template/html"
)

func main() {
    app := fiber.New(fiber.Config{
        Views: html.New("./views", ".html"),
    })

    app.Get("/", func(c *fiber.Ctx) error {
      return c.Render("index", fiber.Map{
         "Title": "Hello, World!",
      })
    })

    log.Fatal(app.Listen(":3000"))
}

WebSocket支持

在您的Fiber应用程序中使用WebSockets的强大功能!保证性能和可扩展性,以构建快速的交互式用户体验。

app.Get("/ws", websocket.New(func(c *websocket.Conn) {
  // Websocket logic
  for {
    mtype, msg, err := c.ReadMessage()
    if err != nil {
      break
    }
    log.Printf("Read: %s", msg)

    err = c.WriteMessage(mtype, msg)
    if err != nil {
      break
    }
  }
  log.Println("Error:", err)
}))

速率限制器

使用Fiber,将重复请求限制为公共API和端点非常简单。

Internal Middleware

Here is a list of middleware that are included within the Fiber framework.

Middleware Description
basicauth Basic auth middleware provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized for missing or invalid credentials.
compress Compression middleware for Fiber, it supports deflate, gzip and brotli by default.
cache Intercept and cache responses
cors Enable cross-origin resource sharing (CORS) with various options.
csrf Protect from CSRF exploits.
filesystem FileSystem middleware for Fiber, special thanks and credits to Alireza Salary
favicon Ignore favicon from logs or serve from memory if a file path is provided.
limiter Rate-limiting middleware for Fiber. Use to limit repeated requests to public APIs and/or endpoints such as password reset.
logger HTTP request/response logger.
pprof Special thanks to Matthew Lee (@mthli)
proxy Allows you to proxy requests to a multiple servers
requestid Adds a requestid to every request.
recover Recover middleware recovers from panics anywhere in the stack chain and handles the control to the centralized ErrorHandler.
timeout Adds a max time for a request and forwards to ErrorHandler if it is exceeded.

🧬 External Middleware

List of externally hosted middleware modules and maintained by the Fiber team.

Middleware Description
adaptor Converter for net/http handlers to/from Fiber request handlers, special thanks to @arsmn!
helmet Helps secure your apps by setting various HTTP headers.
jwt JWT returns a JSON Web Token (JWT) auth middleware.
keyauth Key auth middleware provides a key based authentication.
rewrite Rewrite middleware rewrites the URL path based on provided rules. It can be helpful for backward compatibility or just creating cleaner and more descriptive links.
session This session middleware is build on top of fasthttp/session by @savsgio MIT. Special thanks to @thomasvvugt for helping with this middleware.
template This package contains 8 template engines that can be used with Fiber v1.10.x Go version 1.13 or higher is required.
websocket Based on Fasthttp WebSocket for Fiber with Locals support!

🌱 第三方中间件

这是由Fiber社区创建的中间件列表,如果您想看到自己的中间件,请创建PR

代码 https://github.com/gofiber/fiber

官网 https://gofiber.io/

文档 https://docs.gofiber.io/

示例 https://github.com/gofiber/recipes

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容

  • Awesome GitHub Topic for Go Awesome Go golang-open-source...
    Liam_ml阅读 3,716评论 2 14
  • 背景 掌握了 Go 语言的基础后就该开始实践了,编写Web应用首先需要一个 web 开发框架。做框架选型时,处理w...
    张云飞Vir阅读 7,201评论 0 6
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,656评论 18 139
  • Faygo 框架 Faygo 使用全新架构,是最合适开发API接口的Go Web框架。用户只需定义一个struct...
    Andeya阅读 21,707评论 5 27
  • 推荐指数: 6.0 书籍主旨关键词:特权、焦点、注意力、语言联想、情景联想 观点: 1.统计学现在叫数据分析,社会...
    Jenaral阅读 5,721评论 0 5