小编Teo*_*dor的帖子

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

我制作了一个应用程序,我需要将相同的文件提供给多个路由,因为前端是一个 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 应用程序中拥有的每个视图定义一个路由。

routing go gorilla

8
推荐指数
1
解决办法
5176
查看次数

标签 统计

go ×1

gorilla ×1

routing ×1