go - Go中使用<img>标签显示本 map 片

标签 go image

我如何使用 <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/

相关文章:

iphone - 在 Core Graphics 中调整图像大小

json - 在 Go 中将 YAML 转换为 JSON

json - 尝试解码映射[优先级]字符串

go - 调试golang可执行文件时无法在vscode中获取局部变量

image - 从 dataDirectory 文件路径设置为 img 的 src

image - 如何在 Flutter 中将图像转换为文件?

go - 为什么改变范围内的 slice 长度,值不受影响?

go - 为什么 "go list -m all"命令列出了我的项目中一些未使用的模块?

iphone - MFMailComposeViewController 图像方向

ios - iPad 横向启动图像逆时针旋转 90 度