英文:
Trying to get an image showed in golang template
问题
我正在使用golang设置一个服务器,并在其中执行模板。在我的模板中,我试图获取一张图片,但是不知何故,我尝试的所有方法都不起作用。控制台显示以下错误:
GET http://localhost:5051/static/photo_2021-06-17_14-18-09.jpg 404 (Not Found)
以下是我的Go代码:
package main
import (
"html/template"
"net/http"
// "io/ioutil"
)
func main() {
http.HandleFunc("/a", indexHandler)
http.ListenAndServe(":5051", nil)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/main.html")
t.ExecuteTemplate(w, "main", struct{}{})
}
以下是模板代码:
{{ define "main" }}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<img src="../static/photo_2021-06-17_14-18-09.jpg">
</div>
</body>
</html>
{{ end }}
谢谢!
英文:
Im using golang to set up a server and im executing templates inside of it. Inside of my templates I'm trying to get an image, but for some reason nothing i try works. In the console it says gives that error:
GET http://localhost:5051/static/photo_2021-06-17_14-18-09.jpg 404 (Not Found)
Go code :
package main
import (
"html/template"
"net/http"
// "io/ioutil"
)
func main() {
http.HandleFunc("/a", indexHandler)
http.ListenAndServe(":5051", nil)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("templates/main.html")
t.ExecuteTemplate(w, "main", struct{}{})
}
Template code:
{{ define "main" }}
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<img src="../static/photo_2021-06-17_14-18-09.jpg">
</div>
</body>
</html>
{{ end }}
Thanks!
答案1
得分: 1
将http.ListenAndServe
这一行代码移动到静态处理程序的下方。
英文:
Move the http.ListenAndServe line below the static handler.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论