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
+13.2k Golang : Read from buffered reader until specific number of bytes
+12.9k Golang : Calculate elapsed years or months since a date
+6.8k Golang : Gargish-English language translator
+15.3k Golang : ROT47 (Caesar cipher by 47 characters) example
+11.4k Swift : Convert (cast) Float to String
+16.2k Golang : Check if a string contains multiple sub-strings in []string?
+12.1k Golang : calculate elapsed run time
+7.7k Golang : Gomobile init produce "iphoneos" cannot be located error
+11.4k Golang : Fuzzy string search or approximate string matching example
+29.1k Golang : Save map/struct to JSON or XML file
+8.4k Golang : Another camera capture GUI application with GTK and OpenCV