Go Fiber 教程展示了如何使用 Fiber 框架在 Golang 中创建简单的 Web 应用程序。
Fiber 是一个简单快速的 Go Web 框架。 Fiber 专注于极致性能和低内存占用。它的灵感来自流行的 Express JS 框架。
Fiber 创建一个 HelloWorld
1
2
3
4
5
6
7
8
9
10
11
12
|
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" )) } |
Fiber 路由
路由将 HTTP 动词(例如 GET、POST、PUT、DELETE)和 URL 路径关联到处理函数。要创建路由,我们使用 Fiber 应用程序对象的函数。
1
2
3
|
app.Get( "/" , func (c *fiber.Ctx) error { ... }) |
这里我们将 GET 请求中发送的 / 路径映射到处理函数。该函数接收一个上下文对象作为参数。它保存 HTTP 请求和响应。
Go Fiber 状态码
HTTP 响应状态代码指示特定 HTTP 请求是否已成功完成。
回答分为五类:
- 信息响应 (100–199)
- 成功响应 (200–299)
- 重定向 (300–399)
- 客户端错误 (400–499)
- 服务器错误 (500–599)
1
2
3
4
5
6
7
8
9
10
11
12
|
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 状态代码。
1
|
app := fiber. New () |
New 函数创建一个新的 Fiber 命名实例。
1
2
3
|
app.Get( "/" , func (c *fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) }) |
Get 函数为 HTTP GET 方法注册一个路由。我们将 / 路径映射到匿名函数;该函数返回 Fiber.StatusOK 代码。
Go Fiber 发送短信
使用 SendString 函数发送文本消息。
1
2
3
4
5
6
7
8
9
10
11
12
|
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 时,我们会收到一条简单的文本消息。
1
2
|
$ curl localhost:3000/text Hello there!! |
Go Fiber headers
请求对象还包括从客户端发送的请求标头。请求标头是 HTTP 标头,其中包含有关要获取的资源以及请求资源的客户端的更多信息。
同样,响应标头包括来自服务器的元信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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 请求标头。在我们的例子中,我们返回用户代理名称。
1
2
|
$ curl localhost:3000 /user-agent curl /7 .74.0 |
Go Fiber 发送文件
SendFile 函数在给定路径传输文件。图像显示在浏览器中。下载功能传输图像;该图像由浏览器作为附件提供。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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 路径。图像存储在数据目录中。
以上就是Go语言入门Go Web Fiber框架快速了解的详细内容,更多关于Go Web Fiber框架的资料请关注服务器之家其它相关文章!
原文链接:https://blog.51cto.com/yuzhou1su/5294274