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

Go Web应用CSS导入失败:MIME类型不匹配问题求助

Go Web应用加载CSS时MIME类型错误问题

遇到的错误提示:

"Refused to apply style from 'http://localhost:8080/api/user/static/styles.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled"

当前项目结构

project-root
├── cmd
│   └── app
│       └── main.go
└── templates
    └── static
        └── styles.css
    └── register.html

尝试过的CSS导入方式(均无效)

<link rel="stylesheet" type="text/css" href="templates/static/styles.css"/>
<link type="text/css" href="static/styles.css">
<link type="text/css" href="/templates/static/styles.css">
<link type="text/css" href="./static/styles.css">

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


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

也尝试添加了以下代码,同样无效:

<base href="/">

使用的路由配置(基于github.com/julienschmidt/httprouter)

func NewRouter(userController *controller.UserController, htmlController *controller.HTMLController) *httprouter.Router {
    router := httprouter.New()

    staticHandler := http.StripPrefix("/templates/static/", http.FileServer(http.Dir("templates/static")))
    router.GET("/templates/static/*filepath", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
        staticHandler.ServeHTTP(w, r)
    })

    //router.ServeFiles("/templates/static/*filepath", http.Dir("templates/static"))
    //router.ServeFiles("/static/*filepath", http.Dir("C:\Users\vadim\IdeaProjects\GoLang\sushkof_test\templates\static"))

    //http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static/"))))
    //router.ServeFiles("/static/*filepath", http.Dir("templates/static"))

    router.GET("/api/user/register", htmlController.RegisterHandler)
    router.GET("/api/user/home", htmlController.HomeHandler)

    router.POST("/api/user/register_user", userController.Save)
    //router.ServeFiles("/templates/*filepath", http.Dir("templates"))
    return router
}

更新:
将main.go移到project-root/main.go时,相对路径可以生效;但如果main.go在cmd/app目录下,即便配置路由和调整CSS导入路径也完全无效。这会不会是IntelliJ IDEA的问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:22:42