尝试在 Golang 模板中显示图像。

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

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 (
	&quot;html/template&quot;
	&quot;net/http&quot;
	// &quot;io/ioutil&quot;
)


func main() {
	http.HandleFunc(&quot;/a&quot;, indexHandler)
	http.ListenAndServe(&quot;:5051&quot;, nil)

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

func indexHandler(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles(&quot;templates/main.html&quot;)
	t.ExecuteTemplate(w, &quot;main&quot;, struct{}{})
}

Template code:

{{ define &quot;main&quot; }}
&lt;html&gt;
    &lt;head&gt;
        &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;div&gt;
            &lt;img src=&quot;../static/photo_2021-06-17_14-18-09.jpg&quot;&gt;
        &lt;/div&gt;
    &lt;/body&gt;
&lt;/html&gt;
{{ end }}

Thanks!

答案1

得分: 1

http.ListenAndServe这一行代码移动到静态处理程序的下方。

英文:

Move the http.ListenAndServe line below the static handler.

huangapple
  • 本文由 发表于 2021年6月18日 04:59:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/68026484.html
匿名

发表评论

匿名网友

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

确定