问题
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:
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.
来源:https://stackoverflow.com/questions/17690230/how-to-serve-static-files-over-http