Sha*_*mal 6 go gorilla next.js
我按照以下示例使用 Golang 和本机包提供 NextJs 前端单页应用程序net/http:
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))
}
Run Code Online (Sandbox Code Playgroud)
它有效。现在我想使用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())
}
Run Code Online (Sandbox Code Playgroud)
index.html file当我在浏览器中导航时,这适用于提供服务localhost:8080,但该页面没有样式、没有图像、也没有 JavaScript。
我尝试使用 中的说明gorilla/mux来提供 SPA,但对于此Next.js应用程序,它找不到文件,并且浏览器会因连接重置错误而出错。
我还需要做什么才能让 CSS、JavaScript 和图像在页面加载时可用?
请尝试
r.PathPrefix("/").Handler(http.FileServer(http.FS(distFS)))
Run Code Online (Sandbox Code Playgroud)
gorilla/mux 将函数的第一个参数解释Handle为模板: https: //pkg.go.dev/github.com/gorilla/mux#Route.Path。
添加路由时请注意顺序:当两条路由匹配相同路径时,第一个添加的路由获胜。
| 归档时间: |
|
| 查看次数: |
4247 次 |
| 最近记录: |