利用 Gorilla/Mux 为 Next.js 前端构建后端服务时,使用原生 net/http 包时,Next.js 应用程序的静态文件(如样式、图像和 JavaScript)无法正确加载。本文介绍了一种解决方法,即使用 gorilla/mux 的 PathPrefix() 方法,将根路径(/)指定为静态文件处理程序的模板,从而使 Gorilla/Mux 能够正确解析和提供这些文件。
我按照此示例使用 golang 和本机 net/http 包提供 nextjs 前端单页应用程序:
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))
}
并且它有效。现在我想使用 gorilla/mux 而不是本机 net/http 包。所以现在我的 main 函数如下所示:
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)
}
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.FS(distFS)))
srv := &http.Server{
Handler: r,
Addr: "0.0.0.0:8080",
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
当我在浏览器中导航到 localhost:8080 时,这适用于提供 index.html 文件 ,但该页面没有样式、没有图像,也没有 javascript。
我尝试使用 gorilla/mux 中的说明来提供 spa,但对于此 next.js 应用程序,它找不到文件,并且浏览器会因连接重置错误而出错。
我还需要做什么才能让 css、javascript 和图像在页面加载时可用?
正确答案
请尝试一下
r.PathPrefix("/").Handler(http.FileServer(http.FS(distFS)))
gorilla/mux 将 handle 函数的第一个参数解释为模板:https://pkg.go.dev/github.com/gorilla/mux#Route.Path。
添加路由时请注意顺序:当两条路由匹配相同路径时,第一个添加的路由获胜。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
