样式表不适用于使用 chi 路由器的 go html 模板

cod*_*eek 0 templates routes go

我正在开发具有以下项目结构的 Go Web 应用程序:

  • 用户界面
    • 模板
      • 登录.tmpl
    • 静止的
      • CSS
        • 主题.css
  • 主程序

我的 main.go 代码(为简洁起见,仅显示相关部分)。我正在使用chi 路由器

func main() {

    r := chi.NewRouter()

    var templates *template.Template
    templates = template.Must(template.ParseGlob("ui/templates/*.tmpl"))

    fileServer := http.FileServer(http.Dir("./ui/static/"))


    r.Handle("/static/", http.StripPrefix("/static/", fileServer))

    log.Fatal(http.ListenAndServe(":8080", r))
}
Run Code Online (Sandbox Code Playgroud)

用于包含CSS的login.tmpl代码:

<head>
    <link rel="stylesheet" href="/static/css/theme.css">
</head>
Run Code Online (Sandbox Code Playgroud)

问题:

当此代码运行时,html 生成正常,但 css 未应用于页面。在 Chrome 控制台中,我看到以下错误:

拒绝应用“ http://localhost:8080/static/css/theme.css ”中的样式,因为其 MIME 类型(“text/plain”)不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

mko*_*iva 5

使用chi路由器时,必须*在模式末尾使用通配符才能使文件服务器正常工作。

r.Handle("/static/*", http.StripPrefix("/static/", fileServer))
Run Code Online (Sandbox Code Playgroud)

https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go