英文:
html page can't find asset from Go web server
问题
我有一个Go HTTP Web服务器,我正在加载静态资源,代码如下:
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))
在Web服务器运行的目录下存在一个名为assets
的目录,以及一个名为assets/images/logo.svg
的图像文件。
如果我尝试访问http://localhost/assets/images/logo.svg
,它会重定向到http://localhost/
。
在HTML页面中,我有以下内容:
<img src="assets/images/logo.svg">
这无法加载图像。
我还尝试了以下内容,但没有成功:
<img src="./assets/images/logo.svg">
<img src="//localhost/assets/images/logo.svg">
不确定我在托管静态文件和在HTML中使用它们方面做错了什么。
编辑
我在这里添加了所有代码。
还附带了一张显示损坏图像的照片。
英文:
I have a Go HTTP web server and I'm loading static assets like so:
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))
The directory assets
exist at the directory the web server is running, and the image file assets/images/logo.svg
exist.
If I try going to http://localhost/assets/images/logo.svg
it redirects to http://localhost/
.
From an HTML page I have the following:
<img src="assets/images/logo.svg">
This fails to load the image.
I then tried the following as well with no luck:
<img src="./assets/images/logo.svg">
<img src="//localhost/assets/images/logo.svg">
Unsure what I'm doing wrong to host static files and being able to use them from html.
EDIT
I've added the code for everything here.
Along with a photo showing the broken images.
答案1
得分: 1
尝试将以下行进行修改:
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("assets/")),
),
)
修改为:
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("./assets/")),
),
)
请注意,你的img
的src
应该是这样的:assets/images/logo.svg
。
编辑:
下面的图片是对评论链接的回应:
英文:
Try to modify the line from:
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("assets/")),
),
)
to
http.Handle(
"/assets/",
http.StripPrefix(
"/assets/",
http.FileServer(http.Dir("./assets/")),
),
)
Please note, your img
->src
should be something like this assets/images/logo.svg
EDITED:
The below image is the response to the comment link:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论