英文:
How to serve static files over http
问题
我正在按照使用Go构建网页的教程进行学习。教程中的所有内容都很容易理解,但我想要扩展一下。具体来说,我想要添加一些静态文件(图片)。我已经阅读了Go文档,并找到了FileServer,并在我的处理程序中添加了以下代码:
http.ServeFile(w, r, "/home/jeff/web/foo.jpg")
我看到了一张被服务的图片,但它没有使用模板中的代码:
<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>
*我也尝试过给出图片的完整路径。
我想要做的是让图片出现在我在模板中精心放置的位置。
我希望图片出现在我指定的位置,但实际上它们是空白的。我没有看到任何错误提示说找不到文件。
我认为这应该是这样工作的(再次强调我没有经验),即告诉服务器我有一个包含一些静态文件的目录,每当模板请求一个图片时,在这里查找并提供服务。看起来并不是这么简单。我做错了什么?我该如何使其工作?
我在我的main
函数中使用了http.ListenAndServe(":8080", nil)
,换句话说,我没有使用Apache或其他Web服务器。
英文:
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.
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?
I'm using http.ListenAndServe(":8080", nil)
in my main
in other words I'm not using apache or some other web-server
答案1
得分: 10
图片应该从不同的URL路径提供给模板。
你需要定义静态文件将从哪里提供,可以使用类似以下的代码:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/home/jeff/web/")))))
然后确保<IMG>
的源URL是这样的:
<img src="/static/foo.jpg" alt="moooooo">
希望能帮到你。
英文:
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/"))))
and then make sure the <IMG>
source URLs are something like:
<img src="/static/foo.jpg" alt="moooooo">
Hope that helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论