为了账号安全,请及时绑定邮箱和手机立即绑定

我尝试从 Go net/http 转换为 Go Fiber,如何进行转换?

我尝试从 Go net/http 转换为 Go Fiber,如何进行转换?

Go
米琪卡哇伊 2022-10-24 10:15:12
我是 golang 的新手,然后我学习了,我喜欢 Go 纤维。我从 Go Fiber 中学习,我看到 net/http 示例非常酷。然后我尝试将 Go net/http 示例转换为 Go 光纤。下面是上网/httppackage mainimport (    "embed"    "io/fs"    "log"    "net/http"    "runtime/pprof")//go:embed nextjs/dist//go:embed nextjs/dist/_next//go:embed nextjs/dist/_next/static/chunks/pages/*.js//go:embed nextjs/dist/_next/static/*/*.jsvar nextFS embed.FSfunc main() {    // Root at the `dist` folder generated by the Next.js app.    distFS, err := fs.Sub(nextFS, "nextjs/dist")    if err != nil {        log.Fatal(err)    }    // The static Next.js app will be served under `/`.    http.Handle("/", http.FileServer(http.FS(distFS)))    // The API will be served under `/api`.    http.HandleFunc("/api", handleAPI)    // Start HTTP server at :8080.    log.Println("Starting HTTP server at http://localhost:8080 ...")    log.Fatal(http.ListenAndServe(":8080", nil))}func handleAPI(w http.ResponseWriter, _ *http.Request) {    // Gather memory allocations profile.    profile := pprof.Lookup("allocs")    // Write profile (human readable, via debug: 1) to HTTP response.    err := profile.WriteTo(w, 1)    if err != nil {        log.Printf("Error: Failed to write allocs profile: %v", err)    }}
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

我认为你可以替换这个:


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

    profile := pprof.Lookup("allocs")

    return c.Get(profile)

  })

有了这个:


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

    profile := pprof.Lookup("allocs")

    return profile.WriteTo(c, 1)

  })

*fiber.Ctximplements io.Writer,因此您应该能够像http.ResponseWriter在这种情况下一样使用它。


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 129 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号