Use <img> tag Go to local image display

How can I use the tag <img> to display local images to Go?

I tried the following:

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

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

If I try http.ServeFile with the same path, I can upload the image, however I would like to embed it in a web page.

+4
source share
2 answers

I will predestinate this by saying that my knowledge of Go is brutal at best, but the few experiments I have done are a bit related to this, so maybe this will at least point you in the right direction. Basically, the code below uses Handle for something under /images/ , which serves the files from the images folder in your root directory (in my case it was /home/username/go ). Then you can either specify hardcode /images/ in the <img> , or use path.Join() as before, making images 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) } 
+7
source

Perhaps you could use a data URI .

+2
source

Source: https://habr.com/ru/post/1439724/


All Articles