ZetCode

Go Fiber

最后修改时间 2024 年 4 月 11 日

在本文中,我们将介绍如何使用 Fiber 框架在 Golang 中创建简单的 Web 应用程序。

关于 Fiber

Fiber 是一个简单而快速的 Go Web 框架。Fiber 专注于极致的性能和低内存占用。它受到了流行的 Express JS 框架的启发。

Fiber 路由

一个 路由 将 HTTP 动词(如 GET、POST、PUT、DELETE)和 URL 路径关联到一个处理函数。要创建路由,我们使用 Fiber 应用程序对象的功能。

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

在这里,我们将 GET 请求中的 / 路径映射到处理函数。该函数接收一个上下文对象作为参数。它包含 HTTP 请求和响应。

Go Fiber 状态码

HTTP 响应状态码指示特定的 HTTP 请求是否已成功完成。

响应分为五类

status.go
package main

import (
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {

        return c.SendStatus(fiber.StatusOK)
    })

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

SendStatus 函数设置 HTTP 状态码。

app := fiber.New()

New 函数创建一个新的 Fiber 命名实例。

app.Get("/", func(c *fiber.Ctx) error {

    return c.SendStatus(fiber.StatusOK)
})

Get 函数为 HTTP GET 方法注册路由。我们将 / 路径映射到一个匿名函数;该函数返回 fiber.StatusOK 码。

Go Fiber 发送文本消息

使用 SendString 函数发送文本消息。

text_message.go
package main

import (
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/text", func(c *fiber.Ctx) error {

        return c.SendString("Hello there!!")
    })

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

当我们访问 localhost:3000/text URL 时,我们会收到一条简单的文本消息。

$ curl localhost:3000/text
Hello there!!

Go Fiber 请求头

请求对象还包括从客户端发送的请求头。请求头是包含有关要获取的资源以及请求该资源的客户端的更多信息的 HTTP 头。

同样,响应头包含来自服务器的元信息。

headers.go
package main

import (
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {

        return c.SendString("Main page")
    })

    app.Get("/user-agent", func(c *fiber.Ctx) error {

        ua := c.Get("User-Agent")

        return c.SendString(ua)
    })

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

Get 函数返回由字段指定的 HTTP 请求头。在我们的例子中,我们返回用户代理名称。

$ curl localhost:3000/user-agent
curl/7.74.0

Go Fiber 发送文件

SendFile 函数传输指定路径的文件。图像会在浏览器中显示。Download 函数传输图像;浏览器会将图像作为附件提供。

send_file.go
package main

import (
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/sid", func(c *fiber.Ctx) error {

        return c.Download("./data/sid.png")
    })

    app.Get("/sid2", func(c *fiber.Ctx) error {

        return c.SendFile("./data/sid.png")
    })

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

在示例中,我们有用于显示和下载图像的 URL 路径。图像存储在 data 目录中。

Go Fiber 查询参数

查询字符串是 URL 的一部分,用于向资源请求添加一些数据。它通常是一系列键/值对。它跟在路径后面,并以 ? 字符开头。

query_string.go
package main

import (
    "fmt"
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/hello", func(c *fiber.Ctx) error {

        name := c.Query("name")
        age := c.Query("age")

        msg := fmt.Sprintf("%s is %s years old", name, age)
        return c.SendString(msg)
    })

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

该应用程序创建并向客户端发送消息。它使用 name 和 age 查询参数的值。

name := c.Query("name")
age := c.Query("age")

Query 函数返回 URL 中的查询字符串参数。

$ curl "localhost:3000/hello?name=Peter&age=45"
Peter is 45 years old

Go Fiber 路径参数

可以通过查询参数或路径参数将值发送到 Web 应用程序。路径参数在冒号 /:param 之后指定。

Params 函数用于获取路由参数。

path_params.go
package main

import (
    "fmt"
    "log"

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

func main() {

    app := fiber.New()

    app.Get("/say/:name/:age/", func(c *fiber.Ctx) error {

        name := c.Params("name")
        age := c.Params("age")

        msg := fmt.Sprintf("%s is %s years old", name, age)
        return c.SendString(msg)
    })

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

程序向用户返回一条消息,其中包含发送的两个路径参数。

app.Get("/say/:name/:age/", func(c *fiber.Ctx) error {

我们使用冒号来表示路径中的参数。

$ curl localhost:3000/say/Lucia/32
Lucia is 32 years old

Go Fiber JSON

JSON 是一种轻量级的数据交换格式。它易于人类阅读,也易于机器解析和生成。Web 应用程序通常会消耗和生成 JSON 数据。

JSON 函数将任何接口或字符串转换为 JSON。数组和切片值被编码为 JSON 数组。

jsonex.go
package main

import (
    "log"

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

type movie struct {
    id    int
    title string
}

func main() {

    app := fiber.New()

    app.Get("/movies", func(c *fiber.Ctx) error {

        movies := map[int]string{1: "Toy story", 2: "The Raid", 3: "Hero",
            4: "Ip Man", 5: "Kung Fu Panda"}

        return c.JSON(movies)
    })

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

该示例以 JSON 格式发送电影数据。

$ curl localhost:3000/movies
{"1":"Toy story","2":"The Raid","3":"Hero","4":"Ip Man","5":"Kung Fu Panda"}

Go Fiber 静态文件

静态文件是不会更改的文件。它们包括 CSS 文件、JavaScript 文件和图像;也包括不包含模板指令的 HTML 文件。

Static 函数创建一个文件服务器来提供静态文件。

public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>

    <p>
        This is home page
    </p>

</body>
</html>

这是主页。它是静态 HTML 文件的一个示例。

static.go
package main

import (
    "log"

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

func main() {

    app := fiber.New()

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

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

代码示例为主页显示了一个简单的静态 HTML 文件。

Go Fiber 模板引擎

模板引擎或模板处理器是一个库,旨在将模板与数据模型结合起来以生成文档。模板引擎用于生成大量电子邮件、在源代码预处理中,或生成动态 HTML 页面。

Fiber 可以使用多种模板引擎,包括 html、pug、handlebars 和 mustache。html 是官方的 Go 模板引擎。

views/show_date.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Show date</title>
</head>
<body>

    <p>
        Today is {{ .now }}
    </p>

</body>
</html>

这是 show_date.html 模板文件。该模板由静态数据和动态数据组成。

<p>
    Today is {{ .now }}
</p>

使用 {{.}} 语法,我们输出传递给模板的 now 变量的值。

template.go
package main

import (
    "log"
    "time"

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

func main() {

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

    app.Get("/now", func(c *fiber.Ctx) error {

        now := time.Now()

        return c.Render("show_date", fiber.Map{
            "now": now.Format("Jan 2, 2006"),
        })
    })

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

在示例中,我们计算当前日期并将其发送到 show_date.html 模板文件进行处理。

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

我们配置了存放模板文件的目录。

return c.Render("show_date", fiber.Map{
    "now": now.Format("Jan 2, 2006"),
})

Render 函数使用数据渲染模板并发送 text/html 响应。

来源

Go Fiber - Github 页面

在本文中,我们使用 Fiber 在 Golang 中创建了简单的 Web 应用程序。

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写超过 1,400 篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Go 教程