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
+12.5k Golang : Compress and decompress file with compress/flate example
+12.1k Golang : Image to ASCII art example
+5.6k Golang : When to use make or new?
+7.4k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+12.9k Golang : Google Drive API upload and rename example
+9.7k Golang : Create Temporary File
+16.1k Golang : Multi threading or run two processes or more example
+8.2k Golang : Detect number of active displays and the display's resolution
+5.9k Golang : constant 20013 overflows byte error message
+10k Golang : Create S3 bucket with official aws-sdk-go package
+14k Golang : Get digits from integer before and after given position example