HTML页面无法从Go Web服务器找到资源。

huangapple go评论82阅读模式
英文:

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中使用它们方面做错了什么。

编辑

我在这里添加了所有代码。
还附带了一张显示损坏图像的照片。

HTML页面无法从Go Web服务器找到资源。

英文:

I have a Go HTTP web server and I'm loading static assets like so:

http.Handle(&quot;/assets/&quot;, http.StripPrefix(&quot;/assets/&quot;, http.FileServer(http.Dir(&quot;assets/&quot;))))

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:

&lt;img src=&quot;assets/images/logo.svg&quot;&gt;

This fails to load the image.

I then tried the following as well with no luck:

&lt;img src=&quot;./assets/images/logo.svg&quot;&gt;
&lt;img src=&quot;//localhost/assets/images/logo.svg&quot;&gt;

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.

HTML页面无法从Go Web服务器找到资源。

答案1

得分: 1

尝试将以下行进行修改:

http.Handle(
    "/assets/",
    http.StripPrefix(
        "/assets/", 
        http.FileServer(http.Dir("assets/")),
    ),
)

修改为:

http.Handle(
    "/assets/", 
    http.StripPrefix(
        "/assets/", 
        http.FileServer(http.Dir("./assets/")),
    ),
)

请注意,你的imgsrc应该是这样的:assets/images/logo.svg

编辑
下面的图片是对评论链接的回应:
HTML页面无法从Go Web服务器找到资源。

英文:

Try to modify the line from:

http.Handle(
    &quot;/assets/&quot;,
    http.StripPrefix(
        &quot;/assets/&quot;, 
        http.FileServer(http.Dir(&quot;assets/&quot;)),
    ),
)

to

http.Handle(
    &quot;/assets/&quot;, 
    http.StripPrefix(
        &quot;/assets/&quot;, 
        http.FileServer(http.Dir(&quot;./assets/&quot;)),
    ),
)

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:
HTML页面无法从Go Web服务器找到资源。

huangapple
  • 本文由 发表于 2022年4月19日 10:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71918931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定