[英]Go Fiber - I try to translate from Go net/http to Go Fiber, how to cenvert it?
我是 golang 的新手,然后我學習了,我喜歡 Go 光纖。 我從 Go 光纖中學習,我看到 net/http 示例非常酷。 然后我嘗試從 Go net/http 示例轉換為 Go 光纖。
下面是 go 網/http
package main
import (
"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/*/*.js
var nextFS embed.FS
func 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)
}
}
我把它改成
package main
import (
"embed"
"log"
// "io/fs"
"runtime/pprof"
"github.com/gofiber/fiber/v2"
)
//go:embed nextjs/dist
//go:embed nextjs/dist/_next
//go:embed nextjs/dist/_next/static/chunks/pages/*.js
//go:embed nextjs/dist/_next/static/*/*.js
var nextFS embed.FS
func main() {
// Root at the `dist` folder generated by the Next.js app.
app := fiber.New()
// The static Next.js app will be served under `/`.
//http.Handle("/", http.FileServer(http.FS(distFS)))
app.Static("/","./nextjs/dist")
// The API will be served under `/api`.
app.Get("/api", func(c *fiber.Ctx) error {
profile := pprof.Lookup("allocs")
return c.Get(profile)
})
// Start HTTP server at :8080.
log.Println("Starting HTTP server at http://localhost:8080 ...")
log.Fatal(app.Listen(":8080"))
}
但我得到如下錯誤:
# command-line-arguments
./main.go:29:17: cannot use profile (type *pprof.Profile) as type string in argument to c.Get
./main.go:29:17: cannot use c.Get(profile) (type string) as type error in return argument:
string does not implement error (missing Error method)
請幫助驗證,我怎樣才能成功獲得 pprof.Lookup("allocs") ? 提前致謝
我認為你可以替換這個:
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.Ctx
實現io.Writer
,所以在這個例子中你應該可以像http.ResponseWriter
一樣使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.