使用gorilla/mux在Golang中创建静态文件服务器

9

我制作了一个应用程序,需要为多个路由提供相同的文件,因为前端是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")

这样做可以使index.html文件在'/'和'/student'路由中都能被访问到。如果我反过来设置,'/student'路径就会出现404错误。所以我的问题是是否有另一种方法可以为这两个路由提供相同的内容,从而避免为我的web应用程序中的每个视图定义一个路由。

1
这个答案被认为是重复[1]的,但它并没有回答 Teodor 的问题。他在原始代码中已经使用了 PathPrefix。1:https://dev59.com/tKHia4cB1Zd3GeqPXbKX - jmaloney
1个回答

17

我曾多次使用这个确切的设置。

你需要一个文件服务器来提供所有静态资源。需要一个文件服务器在所有未处理的路由上提供你的index.html文件。需要一个(我假设是)子路由器来处理所有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))
}

我已经为此苦苦思索了数小时,但这篇文章帮助我在几秒钟内解决了问题。谢谢! - It Assistors
很高兴我能帮到你。 - jmaloney

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接