在Go中使用标签显示本地图像(Use tag in Go to display local image)

编程入门 行业动态 更新时间:2024-10-28 00:23:12
在Go中使用标签显示本地图像(Use tag in Go to display local image)

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

我试过以下内容:

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

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

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

How can I use the <img> tag to display a local image in Go?

I've tried the following:

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

where rootdir = os.Getwd() and fileName is the name of the file.

If I try http.ServeFile with the same path then I can download the image, however I would like to embed it in the webpage itself.

最满意答案

我将在前言中说我的Go知识充其量是残暴的,但我所做的一些实验已经涉及到这一点,所以也许这至少会指向正确的方向。 基本上,下面的代码使用句柄来处理/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) }

I'll preface this by saying my Go knowledge is atrocious at best, but the few experiments I've done have involved this a bit, so maybe this will at least point you in the right direction. Basically, the below code uses a Handle for anything under /images/ that serves files from the images folder in your root directory (in my case it was /home/username/go). You can then either hardcode /images/ in your <img> tag, or use path.Join() as you did before, making images the first argument.

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

更多推荐

本文发布于:2023-08-06 06:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1445051.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图像   标签   tag   image   local

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!