在Go 範本中包含本機JavaScript 檔案
在您的Go 程式碼中,您已經定義了一個包含JavaScript 檔案的網頁模板:
var page = `...<script src="http://localhost:8081/jquery.min.js"></script>...`
但是,您在載入本機jquery.min.js 檔案時遇到問題。以下是解決此問題的方法:
選項1:手動檔案讀取和服務
func SendJqueryJs(w http.ResponseWriter, r *http.Request) { data, err := ioutil.ReadFile("jquery.min.js") if err != nil { http.Error(w, "Couldn't read file", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/javascript") w.Write(data) }
http.HandleFunc("/jquery.min.js", SendJqueryJs) // Register the handler http.ListenAndServe(":8081", nil) // Start the server
選項 2:使用 http.ServeFile
func SendJqueryJs(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "jquery.min.js") }
選項3:使用http.FileServer
staticServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", http.StripPrefix("/static/", staticServer)) http.ListenAndServe(":8081", nil)建立一個http.FileServer 來從目錄中提供靜態檔案:「 🎜>註冊FileServer 處理程序並啟動HTTP伺服器:在這種情況下,您可以將 jquery.min.js 檔案放在 static 目錄中並透過 URL /static/jquery 存取它。 min.js.
以上是如何在 Go Web 模板中包含本機 JavaScript 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!