【问题标题】:Trying to get an image showed in golang template试图在 golang 模板中显示图像
【发布时间】:2021-06-17 20:59:56
【问题描述】:

我正在使用 golang 设置服务器并在其中执行模板。在我的模板中,我试图获取图像,但由于某种原因,我尝试的任何方法都不起作用。在控制台中,它说给出了该错误:

GET http://localhost:5051/static/photo_2021-06-17_14-18-09.jpg 404 (Not Found)

转码:

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 }}

谢谢!

【问题讨论】:

  • 错误是404 (Not found)。这意味着您请求的特定资源(jpeg 文件名)未被服务器定位。
  • 是的,但我不明白这个问题。当我在浏览器中打开 html 文件时,一切都很完美。
  • 你是从static所在的目录运行你的二进制文件吗?
  • 静态处理程序在服务器运行之前没有注册。将呼叫http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) 移动到http.ListenAndServe(":5051", nil) 之前的行。这不是这里的问题,但是您可以通过使用静态目录中文件的绝对 URL 路径来使您的模板位置独立。
  • 成功了!!!!非常感谢!!!!

标签: html go templates


【解决方案1】:

将 http.ListenAndServe 行移到静态处理程序下方。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 2018-09-24
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多