【GO+Fiber】Fiber框架初识-《GO开发知识笔记》

admin 2025-11-04 01:10:19 编程 来源:ZONE.CI 全球网 0 阅读模式
  • 安装
  • 零分配
  • 基本路由
  • 静态文件

    带有示例的在线 API 文档,因此您可以立即开始使用 Fiber 构建 Web 应用程序!Fiber是一个受Express启发的Web 框架,构建在Fasthttp 之上,这是Go中最快的HTTP 引擎。旨在简化快速开发的工作,同时考虑到零内存分配性能。这些文档适用于2020年 9 月 15 日发布的Fiber v2

    安装

    首先,下载并安装 Go。1.14或更高是必需的。使用以下命令完成安装:

    1. go get github.com/gofiber/fiber/v2

    零分配

    • Fiber.Ctx返回的某些值默认情况下不是不可变的。因为 Fiber 针对高性能进行了优化,所以fiber.Ctx返回的值默认情况下不是不可变的,并且会在请求之间重复使用。根据经验,您只能在处理程序中使用上下文值,并且不得保留任何引用。一旦您从处理程序返回,您从上下文中获得的任何值都将在未来的请求中重新使用,并将在您的脚下发生变化。这是一个例子:

      1. func handler(c *fiber.Ctx) error {
      2. // Variable is only valid within this handler
      3. result := c.Params("foo")
      4. // ...
      5. }

      如果您需要在处理程序之外保留这些值,请使用内置的copy 复制其底层缓冲区。这是一个持久化字符串的示例:

      1. func handler(c *fiber.Ctx) error {
      2. // Variable is only valid within this handler
      3. result := c.Params("foo")
      4. // Make a copy
      5. buffer := make([]byte, len(result))
      6. copy(buffer, result)
      7. resultCopy := string(buffer)
      8. // Variable is now valid forever
      9. // ...
      10. }

      我们创建了一个ImmutableString执行上述操作的自定义函数,该函数在gofiber/utils包中可用。

      1. app.Get("/:foo", func(c *fiber.Ctx) error {
      2. // Variable is now immutable
      3. result := utils.ImmutableString(c.Params("foo"))
      4. // ...
      5. })

      或者,您也可以使用该Immutable设置。它将使从上下文返回的所有值不可变,允许您将它们保存在任何地方。当然,这是以性能为代价的。

    下面嵌入本质上是您可以创建的最简单的Fiber应用程序:

    1. package main
    2. import "github.com/gofiber/fiber/v2"
    3. func main() {
    4. app := fiber.New()
    5. app.Get("/", func(c *fiber.Ctx) error {
    6. return c.SendString("Hello, World!")
    7. })
    8. app.Listen(":3000")
    9. }

    浏览到http://localhost:3000,您应该Hello, World!在页面上看到。

    基本路由

    路由是指确定应用程序如何响应客户端对特定端点的请求,该端点是 URI(或路径)和特定的 HTTP 请求方法(GET、PUT、POST等)。每个路由可以有多个处理函数,当路由匹配时执行。路由定义采用以下结构:

    1. // Function signature
    2. app.Method(path string, ...func(*fiber.Ctx) error)
    • app是Fiber的一个实例
    • Method是一个HTTP 请求方法: GET, PUT, POST, 等等。
    • path是服务器上的虚拟路径
    • func(*fiber.Ctx) error是一个回调函数,包含路由匹配时执行的上下文

    简单路线

    1. // Respond with "Hello, World!" on root path, "/"
    2. app.Get("/", func(c *fiber.Ctx) error {
    3. return c.SendString("Hello, World!")
    4. })

    参数

    1. // GET http://localhost:8080/hello%20world
    2. app.Get("/:value", func(c *fiber.Ctx) error {
    3. return c.SendString("value: " + c.Params("value"))
    4. // => Get request with value: hello world
    5. })

    可选参数

    1. // GET http://localhost:3000/john
    2. app.Get("/:name?", func(c *fiber.Ctx) error {
    3. if c.Params("name") != "" {
    4. return c.SendString("Hello " + c.Params("name"))
    5. // => Hello john
    6. }
    7. return c.SendString("Where is john?")
    8. })

    通配符

    1. // GET http://localhost:3000/api/user/john
    2. app.Get("/api/*", func(c *fiber.Ctx) error {
    3. return c.SendString("API path: " + c.Params("*"))
    4. // => API path: user/john
    5. })

    静态文件

    要为图像CSSJavaScript文件等静态文件提供服务,请将您的函数处理程序替换为文件或目录字符串。函数签名:

    1. app.Static(prefix, root string, config ...Static)

    使用以下代码在名为 的目录中提供文件./public:

    1. app := fiber.New()
    2. app.Static("/", "./public")
    3. app.Listen(":3000")

    现在,您可以加载目录中的./public文件:

    1. http://localhost:8080/hello.html
    2. http://localhost:8080/js/jquery.js
    3. http://localhost:8080/css/style.css

    优雅关闭

    1. package main
    2. import (
    3. "log"
    4. "io"
    5. "time"
    6. "net/http"
    7. "github.com/gofiber/fiber/v2"
    8. )
    9. func startHttpServer() *http.Server {
    10. app := fiber.New()
    11. app.Get("/", func(c *fiber.Ctx) error {
    12. return c.SendString("Hello, World!")
    13. })
    14. go func() {
    15. if err := app.Listen(":3000"); err != nil {
    16. // cannot panic, because this probably is an intentional close
    17. log.Printf("Httpserver: ListenAndServe() error: %s", err)
    18. }
    19. }()
    20. // returning reference so caller can call Shutdown()
    21. return app
    22. }
    23. func main() {
    24. log.Printf("main: starting HTTP server")
    25. app := startHttpServer()
    26. log.Printf("main: serving for 10 seconds")
    27. time.Sleep(10 * time.Second)
    28. log.Printf("main: stopping HTTP server")
    29. // now close the server gracefully ("shutdown")
    30. // timeout could be given instead of nil as a https://golang.org/pkg/context/
    31. if err := app.Shutdown(nil); err != nil {
    32. panic(err) // failure/timeout shutting down the server gracefully
    33. }
    34. log.Printf("main: done. exiting")
    35. }

    官方优雅关闭:

    1. package main
    2. import "fmt"
    3. import "os"
    4. import "os/signal"
    5. import "syscall"
    6. func main() {
    7. // Go signal notification works by sending `os.Signal`
    8. // values on a channel. We'll create a channel to
    9. // receive these notifications (we'll also make one to
    10. // notify us when the program can exit).
    11. sigs := make(chan os.Signal, 1)
    12. done := make(chan bool, 1)
    13. // `signal.Notify` registers the given channel to
    14. // receive notifications of the specified signals.
    15. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
    16. // This goroutine executes a blocking receive for
    17. // signals. When it gets one it'll print it out
    18. // and then notify the program that it can finish.
    19. go func() {
    20. sig := <-sigs
    21. fmt.Println()
    22. fmt.Println(sig)
    23. done <- true
    24. }()
    25. // The program will wait here until it gets the
    26. // expected signal (as indicated by the goroutine
    27. // above sending a value on `done`) and then exit.
    28. fmt.Println("awaiting signal")
    29. <-done
    30. fmt.Println("exiting")
    31. }

    示例代码如下:https://stackoverflow.com/questions/39320025/how-to-stop-http-listenandserve

    1. package main
    2. import (
    3. "log"
    4. "io"
    5. "time"
    6. "net/http"
    7. )
    8. func startHttpServer() *http.Server {
    9. srv := &http.Server{Addr: ":8080"}
    10. http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    11. io.WriteString(w, "hello world\n")
    12. })
    13. go func() {
    14. if err := srv.ListenAndServe(); err != nil {
    15. // cannot panic, because this probably is an intentional close
    16. log.Printf("Httpserver: ListenAndServe() error: %s", err)
    17. }
    18. }()
    19. // returning reference so caller can call Shutdown()
    20. return srv
    21. }
    22. func main() {
    23. log.Printf("main: starting HTTP server")
    24. srv := startHttpServer()
    25. log.Printf("main: serving for 10 seconds")
    26. time.Sleep(10 * time.Second)
    27. log.Printf("main: stopping HTTP server")
    28. // now close the server gracefully ("shutdown")
    29. // timeout could be given instead of nil as a https://golang.org/pkg/context/
    30. if err := srv.Shutdown(nil); err != nil {
    31. panic(err) // failure/timeout shutting down the server gracefully
    32. }
    33. log.Printf("main: done. exiting")
    34. }

    参考: https://docs.gofiber.io/api/app

    以太坊cppgolang区别 编程

    以太坊cppgolang区别

    以太坊是一种去中心化的开源平台,它采用智能合约技术,旨在构建和运行不受干扰的分布式应用程序。作为目前最受欢迎的区块链平台之一,以太坊提供了多种编程语言的支持,其
    progolang 编程

    progolang

    Go语言(Golang)是由Google开发的一门静态类型编程语言。作为一名专业的Golang开发者,我深知这门语言的优势和特点。在本文中,我将介绍Golang
    golangn个发送者 编程

    golangn个发送者

    Golang是一种开源的编程语言,由Google团队开发,旨在提高程序的并发性和简化软件开发过程。在Go语言中,有时需要向多个接收者发送信息。本文将介绍如何在G
    golang技能图谱 编程

    golang技能图谱

    从互联网行业的快速发展到人工智能技术的日益成熟,各种编程语言也应运而生。而在这众多的编程语言中,Golang(即Go)作为一门强大且高效的开发语言备受关注。Go
    评论:0   参与:  9