我如何使用 <img>
在 Go 中显示本地镜像的标签?
我试过以下方法:
fmt.Fprintf(w, "</br><img src='" + path.Join(rootdir, fileName) + "' ></img>")
其中 rootdir = os.Getwd() 和 fileName 是文件的名称。
如果我尝试 http.ServeFile
使用相同的路径然后我可以下载图像,但是我想将它嵌入网页本身。
最佳答案
我会先说我的 Go 知识充其量是残酷的,但我所做的一些实验涉及到这一点,所以也许这至少会为您指明正确的方向。基本上,下面的代码对 /images/
下的任何内容都使用句柄。提供来自 images
的文件根目录中的文件夹(在我的例子中是 /home/username/go
)。然后您可以硬编码 /images/
在你的<img>
标记,或使用 path.Join()
和以前一样,制作images
第一个参数。
package main
import (
"fmt"
"net/http"
"os"
"path"
)
func handler(w http.ResponseWriter, r *http.Request) {
fileName := "testfile.jpg"
fmt.Fprintf(w, "<html></br><img src='/images/" + fileName + "' ></html>")
}
func main() {
rootdir, err := os.Getwd()
if err != nil {
rootdir = "No dice"
}
// Handler for anything pointing to /images/
http.Handle("/images/", http.StripPrefix("/images",
http.FileServer(http.Dir(path.Join(rootdir, "images/")))))
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
关于go - Go中使用<img>标签显示本 map 片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12888737/