在Go中使用<img>标签显示本地图像

Mat*_* S. 4 image go

如何使用<img>标签在Go中显示本地图像?

我尝试过以下方法:

fmt.Fprintf(w, "</br><img src='" + path.Join(rootdir,  fileName) + "' ></img>") 
Run Code Online (Sandbox Code Playgroud)

其中rootdir = os.Getwd()和fileName是文件的名称.

如果我尝试http.ServeFile使用相同的路径,那么我可以下载图像,但我想将其嵌入网页本身.

Roc*_*key 7

我要说的是,我的Go知识充其量是残暴的,但我所做的一些实验都涉及到这一点,所以也许这至少会指向正确的方向.基本上,下面的代码使用Handle来处理根目录下/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)
}
Run Code Online (Sandbox Code Playgroud)