How to serve static files(especially images) under protected routes in Chi Router?

283 Views Asked by At

I am using Chi Router and serving files like this:

fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))

In the html file:

<img src="./static/images/img.png" /> 

All's working great and when checking the path of img.png is http://localhost:8080/static/images/img.png WHICH is GOOD... BUT when user visit the profile...

mux.Route("/user", func(mux chi.Router) {
    mux.Use(Auth)
    mux.Get("/profile", handlers.Repo.ProfileGet) // path: /user/profile
})

After the user logs in and visit this path http://localhost:8080/user/profile the images do not appear(because the path has been changed)... When I inspected the image path i found: http://localhost:8080/user/static/images/img.png instead of http://localhost:8080/static/images/img.png

How this issue can be fixed ?

1

There are 1 best solutions below

0
Abd allah Khateeb On BEST ANSWER

The Problem is related to the way relative URLs are resolved in HTML

<img src="./static/images/img.png" />

This path is resolved relative to the current URL in the browser.

To fix this problem use an absolute path for your static resources in your HTML.

<img src="/static/images/img.png" />

By adding a leading /, you're specifying that the path should be resolved from the root of the domain