Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use <img> tag in Go to display local image

Tags:

image

go

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.

like image 993
Matt S. Avatar asked Dec 27 '22 16:12

Matt S.


2 Answers

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)
}
like image 142
RocketDonkey Avatar answered Dec 29 '22 06:12

RocketDonkey


Maybe you could use a data URI.

like image 40
Kyle Finley Avatar answered Dec 29 '22 05:12

Kyle Finley