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
+22.6k Golang : Convert Unix timestamp to UTC timestamp
+5.5k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+11.9k Golang : Find age or leap age from date of birth example
+19.6k Golang : How to count the number of repeated characters in a string?
+5.5k Python : Delay with time.sleep() function example
+26.9k Golang : How to check if a connection to database is still alive ?
+8.4k Golang : Emulate NumPy way of creating matrix example
+14.3k Golang : Check if a file exist or not
+5.7k Clean up Visual Studio For Mac installation failed disk full problem
+46.5k Golang : Read tab delimited file with encoding/csv package
+34.2k Golang : Proper way to set function argument default value
+16.6k Golang : How to implement two-factor authentication?