【问题标题】:Static file server in Golang using gorilla/muxGolang 中使用 gorilla/mux 的静态文件服务器
【发布时间】:2023-06-02 20:12:01
【问题描述】:

我制作了一个应用程序,我需要为多个路由提供相同的文件,因为前端是一个 React 应用程序。我一直在为路由器使用 gorilla mux。 文件结构如下:

main.go
build/
  | index.html
  | service-worker.js
     static/
       |  js/
           | main.js
       |  css/
           | main.css

文件被引用假定它们位于文件目录的根目录。所以在 html 文件中,他们被要求像'/static/js/main.js'。

主要我的路线定义如下:

r.PathPrefix("/student").Handler(http.StripPrefix("/student",http.FileServer(http.Dir("build/")))).Methods("GET")
r.PathPrefix("/").Handler(http.FileServer(http.Dir("build/"))).Methods("GET")

这样我就可以在“/”和“/student”路径中获得 index.html 文件。如果我让它们绕过“/学生”路径,则会出现 404 错误。所以我要问的是,是否有另一种方法可以为这两个路由提供相同的内容,这样我就不必为我的网络应用程序中的每个视图定义一个路由。

【问题讨论】:

  • 这是假定的重复[1] 的答案,不回答 Teodor 的问题。他已经在他的原始代码中使用了 PathPrefix。 1:*.com/questions/43943038/…

标签: go routing gorilla


【解决方案1】:

我已经多次进行过这种精确的设置。

您将需要一个为所有静态资产提供服务的文件服务器。一个文件服务器,用于在所有未处理的路由上为您的 index.html 文件提供服务。 A(我假设)一个子路由器,用于对您的服务器的所有 API 调用。

这是一个应该与您的文件结构相匹配的示例。

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    r := mux.NewRouter()

    // Handle API routes
    api := r.PathPrefix("/api/").Subrouter()
    api.HandleFunc("/student", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "From the API")
    })

    // Serve static files
    r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("./build/static/"))))

    // Serve index page on all unhandled routes
    r.PathPrefix("/").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        http.ServeFile(w, r, "./build/index.html")
    })

    fmt.Println("http://localhost:8888")
    log.Fatal(http.ListenAndServe(":8888", r))
}

【讨论】:

  • 一直在拉我的头发好几个小时试图弄清楚这一点,这帮助我在几秒钟内解决了问题。谢谢
  • 很高兴我能帮上忙
最近更新 更多