英文:
Serving Subdirectories in HTTP handlers [GoLang]
问题
我有以下代码:
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./frontend/build/")))
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/")))
r.PathPrefix("/api").Handler(auth)
/api 应该是安全的。如果用户访问 /,我希望他们能够查看 PROJECTDIR/frontend 目录中的 index.html。
前端目录结构如下:
frontend
/build
index.html
/static
/js
/css
/media
index.html 从 /static 加载所有内容。无论我如何配置,当我访问 localhost:3000 时,我可以获取到 index.html,但是 /static 下的所有内容都是 404。
我配置有什么问题吗?
英文:
I have the following code:
r := mux.NewRouter()
r.Handle("/", http.FileServer(http.Dir("./frontend/build/")))
r.Handle("/static", http.FileServer(http.Dir("./frontend/build/static/")))
r.PathPrefix("/api").Handler(auth)
/api is supposed to be secure. If a user hits /, I want them to view the index.html in the PROJECTDIR/frontend directory.
The frontend directory looks like
frontend
/build
index.html
/static
/js
/css
/media
The index.html loads all contents from /static. No matter how I seem to configure this, when I visit localhost:3000, I can get the index.html but everything under /static is 404'd.
How am I configuring this incorrectly?
答案1
得分: 5
假设您想在端点/static上提供整个"static"目录的内容,并且您正在运行一个BSD/Linux机器,以下语法应该可以工作:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
英文:
Assuming you want to serve the whole content of the directory "static" on the endpoint /static and you are running a bsd/linux machine the following syntax should work:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论