【问题标题】:How to serve a NextJs frontend using Golang (Go) and gorilla/mux?如何使用 Golang (Go) 和 gorilla/mux 为 NextJs 前端提供服务?
【发布时间】: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 mux Handle 处理模式。所以模式/ 将完全匹配。试试 `r.PathPrefix("/").Handle(...))

标签: go next.js gorilla


【解决方案1】:

请尝试

    r.PathPrefix("/").Handler(http.FileServer(http.FS(distFS)))

gorilla/mux 将 Handle 函数的第一个参数解释为模板:https://pkg.go.dev/github.com/gorilla/mux#Route.Path

请注意添加路由时的顺序:当两条路由匹配相同路径时,第一个添加的获胜。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2022-01-20
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多