我正在嵌入我的 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)
uj5u.com熱心網友回復:
我通過將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"/>
那是:
'The static path [/webUI] the original route [public/onsen/...]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338497.html
標籤:走
上一篇:模板無法正確決議嵌入FS
