1

I am trying to serve CSS, JS files but they are not being loaded and it gives 404 status error for each static file except HTMLs. Here is the code

func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*.html")

router.Use(static.Serve("/", static.LocalFile("./web", true)))

// Simple group: v1
v1 := router.Group("/v1")
{
    //v1.Use(static.Serve("/", static.LocalFile("./web", true))) this didn't make it work either 

    v1.GET("/login", getlogin)
    v1.POST("/checkAuthLog", postRegis)
}

// Simple group: v2
v2 := router.Group("/v2")
{
    v2.GET("/login", getlogin)
    v2.POST("/checkAuthLog", postRegis)
}

router.Run(":8080")

}

Normally, without group routing it works fine. But this way, it didn't work no matter how much i tried.

When i check source code of HTML via browser, it links to :

http://localhost:8080/v1/css/style.css

Though, it should be http://localhost:8080/css/style.css. Somehow it is looking at v1 path for css file. Also, In HTML file it links to:

<link rel="stylesheet" type="text/css" href="css/style.css">

I couldn't find where i am wrong.

By the way project structure is like:

-main.go
-templates
----index.html
----login.html 
-web
----css
----fonts
----js
----img

As i mentioned, normally it works when i just type /login but things get messy when it starts with v1/login path.

Lastly here is GIN framework log.

[GIN] 2021/12/08 - 18:13:50 | 200 | 6.7847ms | ::1 | GET "/v1/login"

[GIN] 2021/12/08 - 18:13:50 | 404 | 0s | ::1 | GET "/v1/css/bootstrap.min.css"

[GIN] 2021/12/08 - 18:13:50 | 404 | 0s | ::1 | GET "/v1/css/style.css"

[GIN] 2021/12/08 - 18:13:50 | 404 | 0s | ::1 | GET "/v1/js/script.js"

[GIN] 2021/12/08 - 18:13:50 | 404 | 0s | ::1 | GET "/v1/js/bootstrap.min.js"

[GIN] 2021/12/08 - 18:13:50 | 404 | 0s | ::1 | GET "/v1/js/script.js"

Thanks in advance.

Alteran
  • 91
  • 8
  • 2
    This problem can usually be fixed by having `href`, `src`, etc. be an absolute path, instead of relative. e.g. `href="/css/style.css"` – mkopriva Dec 08 '21 at 15:38
  • OMG it really worked. I didn't know what forward slash is for. Thanks a lot. – Alteran Dec 08 '21 at 16:16
  • 2
    Note that this is simply how browsers resolve paths they find in the HTML. If they find a relative path then they will *append* it to the current page's URL path. If they find an absolute path then they will use that as the current page's URL full path. e.g. if you load the html on `/foo/bar/baz/` and it contains `href="styles.css"` then the browser will request `/foo/bar/baz/styles.css`, but if the html contains `href="/styles.css` the browser will request `/styles.css`. – mkopriva Dec 08 '21 at 16:23

0 Answers0