You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gin框架模板静态资源加载异常:路径自动添加前缀问题

问题:/users/login路径下静态资源加载异常

我在Gin服务器中配置了以下路由:

router.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{"title": "Главная страница"})
})

router.POST("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{"title": "Главная страница"})
})

router.GET("/users", func(c *gin.Context) {
    c.HTML(http.StatusOK, "register.html", gin.H{"title": "Регистрация"})
})

router.POST("/users", server.createUser, func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{"title": "Регистрация"})
})

router.GET("/users/login", func(c *gin.Context) {
    c.HTML(http.StatusOK, "auth.html", gin.H{"title": "Авторизация"})
})
router.POST("/users/login", server.loginUser, func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.html", gin.H{"title": "Главная страница"})
})

访问/users时一切正常,但访问/users/login时样式无法加载。控制台输出如下:

[GIN] 2023/03/29 - 20:06:31 | 200 |      4.4518ms |             ::1 | GET      "/users/login"
[GIN] 2023/03/29 - 20:06:31 | 404 |            0s |             ::1 | GET      "/users/static/css/styles.css"
[GIN] 2023/03/29 - 20:06:32 | 200 |    123.6236ms |             ::1 | GET      "/static/css/auth.css"
[GIN] 2023/03/29 - 20:07:04 | 200 |       3.594ms |             ::1 | GET      "/users"
[GIN] 2023/03/29 - 20:07:04 | 304 |       444.2µs |             ::1 | GET      "/static/css/register.css"

可见访问/users时静态资源请求路径为/static/css/file.css,是正确的;但访问/users/login时,请求路径变成了/users/static/css/styles.css,自动添加了users前缀。我的HTML模板中资源链接如下:

register.html中:

<link rel="stylesheet" href="/static/css/register.css">

auth.html中:

<link rel="stylesheet" href="/static/css/auth.css">

为何两者的静态资源加载路径会出现差异?


解答

从控制台日志能看到,访问/users/login时首先出现了一个404请求/users/static/css/styles.css,这说明auth.html里实际存在一个未添加根路径前缀(/)的资源引用,比如写成了static/css/styles.css,而非你贴出的/static/css/auth.css。

你提供的auth.html代码里的auth.css路径是正确的(带/),所以后续该请求返回200,但那个styles.css的引用是相对路径,浏览器会将其视为相对于当前页面路径/users/login的资源,因此拼接成了/users/static/css/styles.css,导致404错误。

解决步骤:

  • 检查auth.html的完整代码,找到所有静态资源(CSS、JS、图片等)的引用,确保所有路径都以/开头,使用绝对路径(如/static/css/styles.css),这样浏览器会从网站根目录开始查找资源,不受当前页面路径影响。
  • 确认Gin中已正确配置静态文件服务,比如执行router.Static("/static", "./static"),确保根目录下的static文件夹可被正常访问。

内容的提问来源于stack exchange,提问作者pizhlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:15:38