我该如何使用 <img>
标签在 Go 中显示本地图片?
我已经尝试了以下方法:
fmt.Fprintf(w, "</br><img src='" + path.Join(rootdir, fileName) + "' ></img>")
其中rootdir = os.Getwd(),fileName是文件名。
如果我使用相同的路径尝试http.ServeFile
,那么我可以下载图片,但是我想将其嵌入到网页中。
/images/
下的所有内容,并从根目录下的 images
文件夹中提供文件(在我的情况下是 /home/username/go
)。然后,你可以在<img>
标签中硬编码/images/
,或者像之前一样使用 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)
}
package main
import (
"io"
"net/http"
"os"
)
func index(w http.ResponseWriter, r *http.Request) {
f, e := os.Open(r.URL.Path[1:])
if e != nil {
panic(e)
}
defer f.Close()
io.Copy(w, f)
}
func main() {
http.HandleFunc("/", index)
new(http.Server).ListenAndServe()
}