Golang : How to display image file or expose CSS, JS files from localhost?
Problem :
You execute your Golang program on localhost
and want to see images on localhost:8080
, but your <img>
HTML tag is not able to pickup the image file location. This also applicable to all the file types that you want to expose to the world via your webserver. For example, CSS files or JavaScript JS files.
Solution :
You need to expose the directory which contain the image file, CSS or JS files with http.FileServer(http.Dir("./"))
functions.
NOTE : Basically, the Golang's webserver will not be able to find the require files - image, CSS, JS - unless they are accessible by the client. Which usually is the Internet browser.
The following code example is a fragment taken from previous tutorial on how to verify token with Google Authenticator App.
func Home(w http.ResponseWriter, r *http.Request) {
//w.Write([]byte(fmt.Sprintf("Generating QR code\n")))
// generate a random string - preferbly 6 or 8 characters
randomStr := randStr(6, "alphanum")
// For Google Authenticator purpose
// for more details see
// https://github.com/google/google-authenticator/wiki/Key-Uri-Format
secret = base32.StdEncoding.EncodeToString([]byte(randomStr))
//w.Write([]byte(fmt.Sprintf("Secret : %s !\n", secret)))
// authentication link. Remember to replace SocketLoop with yours.
// for more details see
// https://github.com/google/google-authenticator/wiki/Key-Uri-Format
authLink := "otpauth://totp/SocketLoop?secret=" + secret + "&issuer=SocketLoop"
// Encode authLink to QR codes
// qr.H = 65% redundant level
// see https://godoc.org/code.google.com/p/rsc/qr#Level
code, err := qr.Encode(authLink, qr.H)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
imgByte := code.PNG()
// convert byte to image for saving to file
img, _, _ := image.Decode(bytes.NewReader(imgByte))
err = imaging.Save(img, "./QRImgGA.png")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// in real world application, the QRImgGA.png file should
// be a temporary file with dynamic name.
// for this tutorial sake, we keep it as static name.
w.Write([]byte(fmt.Sprintf("<html><body><h1>QR code for : %s</h1><img src='http://localhost:8080/QRImgGA.png'>", authLink)))
w.Write([]byte(fmt.Sprintf("<form action='http://localhost:8080/verify' method='post'>Token : <input name='token' id='token'><input type='submit' value='Verify Token'></form></body></html>")))
}
func main() {
http.HandleFunc("/", Home)
http.HandleFunc("/verify", Verify)
// this is for displaying the QRImgGA.png from the source directory
http.Handle("/QRImgGA.png", http.FileServer(http.Dir("./"))) //<---------------- here!
http.ListenAndServe(":8080", nil)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.5k Golang : Experimental emojis or emoticons icons programming language
+7.3k Golang : Rename part of filename
+12.6k Golang : Convert int(year) to time.Time type
+9k Golang : does not implement flag.Value (missing Set method)
+7.4k Golang : Command line ticker to show work in progress
+20.9k Golang : Convert(cast) string to rune and back to string example
+18.9k Golang : Check if directory exist and create if does not exist
+4.7k Javascript : How to get width and height of a div?
+19.9k Swift : Convert (cast) Int to int32 or Uint32
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+6.8k Golang : Find the shortest line of text example