【发布时间】:2022-01-27 13:51:19
【问题描述】:
我关注 this example 使用 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 file 提供服务,但页面没有样式、没有图像,也没有 JavaScript。
我尝试使用 gorilla/mux 处的说明来提供 SPA,但对于这个 Next.js 应用程序,它找不到文件并且浏览器会出现连接重置错误。
我还需要做什么才能让 CSS、JavaScript 和图像在页面加载时可用?
【问题讨论】:
-
stdlib
Handle函数使用前缀(注意终止斜线),而 gorilla muxHandle处理模式。所以模式/将完全匹配。试试 `r.PathPrefix("/").Handle(...))