Home > other >  html page can't find asset from Go web server
html page can't find asset from Go web server

Time:04-20

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 enter image description here

CodePudding user response:

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 enter image description here

  • Related