英文:
Go server not serving files properly
问题
我正在创建一个单页应用程序(SPA)。
我试图用index.html来响应所有的请求(我在前端处理路由)。
我的目录结构如下:
后端
-- main.go
前端
..(其他文件)..
-- index.html
整个项目位于"C:\Go\Projects\src\github.com\congrady\Bakalarka"目录下。
我的main.go文件如下:
package main
import (
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "../Frontend/index.html")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
当我运行main.go文件(使用go run)时,我的本地主机总是响应"404页面未找到"。
当我尝试使用fmt来提供静态内容时,一切都正常工作。
请帮忙,我已经卡在这个问题上很长时间了,但无法使其正常工作。
谢谢。
英文:
I am creating a SPA.
I am trying to respond all requests with index.html
(I handle routing on the frontend).
My directory structure look like this:
Backend
-- main.go
Frontend
..(some other files)..
-- index.html
Whole project is located in "C:\Go\Projects\src\github.com\congrady\Bakalarka"
My main.go file looks like this:
package main
import (
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "../Frontend/index.html")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
When I run my main.go file (using go run), my localhost always responds with "404 page not found".
When I try to serve static content using fmt, everything works fine.
Please help, I'm stuck on this for a really long time and I can't get it to work.
Thanks
答案1
得分: 0
请注意,如果在源文件中硬编码了相对路径,那么启动应用程序时所在的目录是很重要的。
在当前配置中,请确保从Backend
目录启动应用程序,即
C:\Go\Projects\src\github.com\congrady\Bakalarka\Backend,
而不是您应用程序的根目录
C:\Go\Projects\src\github.com\congrady\Bakalarka,
或者
将主文件中的字符串更改为Frontend/index.html,然后从
C:\Go\Projects\src\github.com\congrady\Bakalarka 运行。
英文:
Be aware that if you hardcode relative paths in your source file, the directory which you are in when starting the app matters.
In the current configuration, make sure to start the app from the Backend
directory, i.e.
C:\Go\Projects\src\github.com\congrady\Bakalarka\Backend,
NOT your apps root directory
C:\Go\Projects\src\github.com\congrady\Bakalarka
or
change the string in the main file to Frontend/index.html and run from
C:\Go\Projects\src\github.com\congrady\Bakalarka
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论