样式表不适用于使用 chi 路由器的 go html 模板
Stylesheet does not apply in go html template using chi router
我正在开发具有以下项目结构的 Go Web 应用程序:
- ui
- 模板
- login.tmpl
- 静态
- css
- theme.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))
}
login.tmpl 包含 css:
的代码
<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
我正在开发具有以下项目结构的 Go Web 应用程序:
- ui
- 模板
- login.tmpl
- 静态
- css
- theme.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))
}
login.tmpl 包含 css:
的代码<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