GoFiber教程展示了如何使用Fiber框架在Golang中创建简单的Web应用程序。
$ go version go version go1.18.1 linux/amd64
我们使用Go版本1.18。
关于纤维
Fiber是一个简单快速的Go网络框架。Fiber专注于极致性能和低内存占用。它的灵感来自流行的ExpressJS框架。
光纤线路
路由将HTTP动词(例如GET、POST、PUT、DELETE)和处理程序函数的URL路径相关联。要创建路由,我们使用Fiber应用程序对象的函数。
app.Get("/", func(c *fiber.Ctx) error {
...
})
这里我们将GET请求中发送的/路径映射到handlerfunction。该函数接收一个上下文对象作为参数。它包含HTTP请求和响应。
GoFiber状态码
HTTP响应状态代码指示特定HTTP请求是否已成功完成。
响应分为五类:
- 信息响应(100-199)
- 成功响应(200-299)
- 重定向(300-399)
- 客户端错误(400-499)
- 服务器错误(500-599)
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函数为HTTPGET方法注册一个路由。我们将/路径映射到一个匿名函数;该函数返回fiber.StatusOK代码。
GoFiber发送短信
使用SendString函数发送短信。
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/textURL时,我们会收到一条简单的文本消息。
$ curl localhost:3000/text Hello there!!
Go光纤头
请求对象还包括从客户端发送的请求标头。请求标头是HTTP标头,其中包含有关要获取的资源以及请求资源的客户端的更多信息。
同样,响应标头包含来自服务器的元信息。
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
GoFiber发送文件
SendFile函数在给定路径传输文件。图像显示在浏览器中。Download函数传输图像;该图像由浏览器作为附件提供。
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目录中。
GoFiber查询参数
查询字符串是URL的一部分,用于向资源请求添加一些数据。它通常是一系列键/值对。它遵循路径并以?性格。
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光纤路径参数
值可以通过查询参数或路径参数发送到网络应用程序。路径参数在冒号/:param之后指定。
Params函数用于获取路由参数。
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
GoFiberJSON
JSON是一种轻量级数据交换格式。它易于人类阅读和机器解析和生成。Web应用程序经常使用和生成JSON数据。
JSON函数将任何接口或字符串转换为JSON。数组和切片值编码为JSON数组。
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"}
GoFiber静态文件
静态文件是不会改变的文件。它们包括CSS文件、JavaScript文件和图像;也包括不包含模板指令的HTML文件。
Static函数创建一个提供静态文件的文件服务器。
<!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文件的示例。
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文件。
GoFiber模板引擎
模板引擎或模板处理器是一个库,旨在将模板与数据模型结合起来以生成文档。模板引擎用于生成大量电子邮件、源代码预处理或生成动态HTML页面。
Fiber可以使用多种模板引擎,包括html、pug、handlebars和mustache。html是官方的Go模板引擎。
<!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变量的值。
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函数使用数据呈现模板并发送文本/html响应。
在本教程中,我们使用Fiber在Golang中创建了简单的Web应用程序。
列出所有Go教程。
