gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:17 26 4
gpt4 key购买 nike

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

  • 用户界面
    • 模板
      • 登录.tmpl
    • 静态的
      • CSS
        • 主题.css
  • main.go

我的 main.go 代码(为简洁起见只显示相关部分)。我正在使用 chi router .

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))
}

包含css的login.tmpl代码:

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

问题:

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

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

最佳答案

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

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

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

关于templates - 样式表不适用于使用 chi 路由器的 go html 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57811896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com