如何通过HTTP提供静态文件 [英] How to serve static files over http

查看:56
本文介绍了如何通过HTTP提供静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注有关在go中构建网页的教程.本教程中的所有内容都很容易理解,但是我正在尝试对其进行扩展.具体来说,我正在尝试添加一些静态文件(图片).我一直在浏览文档,发现 FileServer 并添加

I'm following a tutorial on building a webpage in go. Everything in the tutorial is easy to grasp, but I'm trying to expand on it. Specifically, I'm trying to add some static files (pictures). I've been going through the go docs and came across FileServer and adding

http.ServeFile(w, r, "/home/jeff/web/foo.jpg")

在我的处理程序中,我看到正在提供图片,但没有使用模板

in my handler I see an image being served but it's not using the template

<h1>{{.Title}}</h1>
<p>[<a href="/edit/{{.Title}}">edit</a>]</p>

<img src="foo.jpg" alt="moooooo">
<img src="foo.jpg" alt="foooooo">

<div>{{printf "%s" .Body}}</div>

*我也尝试过提供图像的完整路径.

*I've tried giving the full path to the images too.

我想做的是让图像占据我在模板中仔细放置的html标签.

What I'm trying to do is get the image to occupy the html tags that I've placed so carefully in the template.

我希望图像显示在我告诉他们的位置,但是要获得空白图像.我没有看到任何错误,指出找不到该文件.

I want the image to appear where I tell them to, but get blank images where they should be. I'm not seeing any errors saying the file can't be found.

我认为这应该工作的方式(再次没有经验)是告诉服务器我有这个目录,其中包含一些静态文件,并且每当模板在此处请求图像时检查是否存在,如果找到则提供服务.似乎不是那么简单.我究竟做错了什么?我怎样才能使它正常工作?

The way I think this should work (again no experience in this) is by telling the server I have this directory that houses some static files and whenever a template requests an image check here and if found serve it. Doesn't appear to be this simple. What am I doing wrong? How can I get this to work?

我在 main 中使用 http.ListenAndServe(:8080",nil),换句话说,我没有使用apache或其他Web服务器

I'm using http.ListenAndServe(":8080", nil) in my main in other words I'm not using apache or some other web-server

推荐答案

图像应从模板的其他URL路径提供.

The images should be served from a different URL path to the templates.

您需要使用类似以下的命令来定义将在哪里提供静态文件:

You need to define where the static files will be served from using something like:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/jeff/web/"))))

,然后确保< IMG> 源URL类似于:

and then make sure the <IMG> source URLs are something like:

<img src="/static/foo.jpg" alt="moooooo">

希望有帮助.

这篇关于如何通过HTTP提供静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆