Golang 中使用 gorilla/mux 的静态文件服务器

Teo*_*dor 8 routing go gorilla

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

main.go
build/
  | index.html
  | service-worker.js
     static/
       |  js/
           | main.js
       |  css/
           | main.css
Run Code Online (Sandbox Code Playgroud)

这些文件假定它们位于文件目录的根目录中。所以在 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")
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我可以在 '/' 和 '/student' 路由中获得 index.html 文件。如果我将它们放在“/student”路径的另一侧,则会出现 404 错误。所以我要问的是,是否有另一种方法可以为这两个路由提供相同的内容,以便我不必为我将在我的 Web 应用程序中拥有的每个视图定义一个路由。

jma*_*ney 13

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

您将需要一个为所有静态资产提供服务的文件服务器。一个文件服务器,用于在所有未处理的路由上为您的 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))
}
Run Code Online (Sandbox Code Playgroud)