html page can't find asset from Go web server

Issue

I have a Go HTTP web server and I’m loading static assets like so:

http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))

The directory assets exist at the directory the web server is running, and the image file assets/images/logo.svg exist.

If I try going to http://localhost/assets/images/logo.svg it redirects to http://localhost/.

From an HTML page I have the following:

<img src="assets/images/logo.svg">

This fails to load the image.

I then tried the following as well with no luck:

<img src="./assets/images/logo.svg">
<img src="//localhost/assets/images/logo.svg">

Unsure what I’m doing wrong to host static files and being able to use them from html.

EDIT

I’ve added the code for everything here.
Along with a photo showing the broken images.

enter image description here

Solution

Try to modify the line from:

http.Handle(
    "/assets/",
    http.StripPrefix(
        "/assets/", 
        http.FileServer(http.Dir("assets/")),
    ),
)

to

http.Handle(
    "/assets/", 
    http.StripPrefix(
        "/assets/", 
        http.FileServer(http.Dir("./assets/")),
    ),
)

Please note, your img->src should be something like this assets/images/logo.svg

EDITED:
The below image is the response to the comment link:
enter image description here

Answered By – Kishore

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.