使用大猩猩/ mux的Golang中的静态文件服务器 [英] Static file server in Golang using gorilla/mux
问题描述
我制作了一个应用,在其中我需要将相同的文件提供给多个路径,因为前端是一个React应用。我一直在使用大猩猩多路复用器作为路由器。
文件结构如下:
I have made a app where I need to serve the same files to multiple routes because the front end is a React app. I have been using gorilla mux for the router. The file structure is as follows:
main.go
build/
| index.html
| service-worker.js
static/
| js/
| main.js
| css/
| main.css
引用文件是假设它们位于文件目录的根目录中。因此,在html文件中,它们像 /static/js/main.js一样被请求。
The files are refereed to assuming they are at the root of the file directory. So in the html file they are requested like '/static/js/main.js'.
主要,我的路线定义如下:
In main my routes are defined as follows:
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错误。因此,我要问的是还有另一种方式可以为这两个路线提供相同的内容,以使我不必为将在Web应用程序中使用的每个视图定义路线。
This way I get the index.html file served in both the '/' and '/student' route. If I have them the other way around the '/student' path gets a 404 error. So what I am asking is there another way to serve the same content for both of these routes in order for me not have to define a route for each view I will have in my web app.
推荐答案
我已经在多个场合进行了精确的设置。
I've had this exact setup on multiple occasions.
您将需要一个文件服务器,该文件服务器可为所有静态资产。在所有未处理的路由上提供index.html文件的文件服务器。 (我假设)一个子路由器,用于对服务器的所有API调用。
You will need a file server that serves all static assets. A file server to serve your index.html file on all unhandled routes. A (I assume) a sub router for all API calls to your server.
这里是一个与您的文件结构匹配的示例。
Here is an example that should match your file structure.
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))
}
这篇关于使用大猩猩/ mux的Golang中的静态文件服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!