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

  • arsmn/fiber-casbin
  • arsmn/fiber-introspect
  • arsmn/fiber-swagger
  • arsmn/gqlgen
  • codemicro/fiber-cache
  • sujit-baniya/fiber-boilerplate
  • juandiii/go-jwk-security
  • kiyonlin/fiber_limiter
  • shareed2k/fiber_limiter
  • shareed2k/fiber_tracing
  • thomasvvugt/fiber-boilerplate
  • ansrivas/fiberprometheus
  • LdDl/fiber-long-poll
  • K0enM/fiber_vhost
  • theArtechnology/fiber-inertia

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

官网 https://gofiber.io/

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

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

你可能感兴趣的:(Go Web框架 Fiber)