本篇文章就来介绍《无法调用嵌入的 CSS/js 文件》,涉及到,有需要的可以收藏一下
问题内容
我正在嵌入我的 css 和 js 文件,如下所示:
package resources
import (
"embed"
)
// WEBui is our static web ui from onsen ui.
//Go:embed public/onsen
var webui embed.fs
// views is our static web server layouts, views with dynamic content and partials content that is a static view.
//go:embed templates/layouts templates/views templates/partials
var views embed.fs
并尝试在我的主函数中将这个 webui 定义为 static 文件夹:
package main
import (
"fmt"
"log"
"html/template"
"net/Http"
"onsen/resources"
)
var view *template.template
var err error
func init() {
fmt.println("starting up.")
view = template.must(template.parsefs(resources.views, "templates/layouts/*.html", "templates/views/*.html", "templates/partials/*.html"))
if err != nil {
log.fatal("error loading templates:" + err.error())
}
}
func main() {
http.handle("/static/", http.stripprefix("/static/", http.fileserver(http.fs(resources.webui))))
//http.handle("/static/", http.fileserver(http.fs(resources.webui)))
http.handlefunc("/index", index)
server := http.server{
addr: "127.0.0.1:8070",
}
server.listenandserve()
}
func index(w http.responsewriter, r *http.request) {
err = view.executetemplate(w, "index.html", nil)
if err != nil {
log.fatalln(err)
}
}
文件夹结构如图:
但是运行时,我收到以下错误:
CSS files: Refused to apply style from 'http://127.0.0.1:8070/static/css/onsenui.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
JS files: Failed to load resource: the server responded with a status of 404 (Not Found)
正确答案
我通过将 static 路线修复为:
http.handle("/webui/", http.stripprefix("/webui/", http.fileserver(http.fs(resources.webui))))
css 和 js 文件调用如下:
<link rel="stylesheet" type="text/css" href="/webUI/public/onsen/css/onsenui.css"/>
即: '静态路径[/webui] + 原始路由[public/onsen/...]
今天带大家了解了的相关知识,希望对你有所帮助;