我有一個 GoLang 腳本,旨在根據我的瀏覽器中的輸入查詢動態構建網頁,如下所示http://localhost:8000/blog/post#,該post#部分用于識別要決議到我創建的 HTML 模板中的 JSON 資料檔案;例如,如果我把它從我的檔案中http://localhost:8000/blog/post1創建一個檔案。目前,我的腳本在運行時允許我在瀏覽器中加載單個頁面,然后在終端標準輸出日志中出現錯誤退出:index.htmlpost1.json
2022/03/18 00:32:02 error: open jsofun.css.json: no such file or directory
exit status 1
這是我當前的腳本:
package main
import (
"encoding/json"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
)
func blogHandler(w http.ResponseWriter, r *http.Request) {
blogstr := r.URL.Path[len("/blog/"):]
blogstr = blogstr ".json"
// read the file in locally
json_file, err := ioutil.ReadFile(blogstr)
if err != nil {
log.Fatal("error: ", err)
}
// define a data structure
type BlogPost struct {
// In order to see these elements later, these fields must be exported
// this means capitalized naming and the json field identified at the end
Title string `json:"title"`
Timestamp string `json:"timestamp"`
Main string `json:"main"`
ContentInfo string `json:"content_info"`
}
// json data
var obj BlogPost
err = json.Unmarshal(json_file, &obj)
if err != nil {
log.Fatal("error: ", err)
}
tmpl, err := template.ParseFiles("./blogtemplate.html")
HTMLfile, err := os.Create("index.html")
if err != nil {
log.Fatal(err)
}
defer HTMLfile.Close()
tmpl.Execute(HTMLfile, obj)
http.ServeFile(w, r, "./index.html")
}
func main() {
http.HandleFunc("/blog/", blogHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
我已經做了一些基本的除錯,并確定問題出在以下幾行:
json_file, err := ioutil.ReadFile(blogstr)
if err != nil {
log.Fatal("error: ", err)
}
What confuses me is why the ioutil.ReadFile is also trying to read files linked within my HTML? Shouldn't the browser be handling that linkage and not my Handler? For reference this is my HTML where the file jsofun.css is linked; the error referenced in my console output shows me my script is trying to access this file as jsofun.css.json during the call to ioutil.ReadFile:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic JSON Events</title>
<link rel="stylesheet" href="./jsofun.css"></style>
</head>
<body>
<section id="title">
<h1 id="text-title">{{.Title}}</h1>
<time id="timestamp">
{{.Timestamp}}
</time>
</section>
<nav role="navigation" id="site-nav">
<ul id="sitemap">
</ul>
</nav>
<main role="main" id="main">
{{.Main}}
</main>
<footer role="contentinfo" id="footer">
<section id="content-info" role="contentinfo">
{{.ContentInfo}}
</section>
<form id="contact-form" role="form">
<address>
Contact me by <a id="my-email" href="mailto:[email protected]" class="my-email">e-mail</a>
</address>
</form>
</footer>
<script src="./jsofun.js">
</script>
</body>
</html>
I know that I have appended .json to my query string in the line: blogstr = blogstr ".json", however, I do not see why this would also affect the links in my HTML. Is there something I am missing or why would it be reading links in my HTML template? All I want the ioutil.ReadFile to do is to read my JSON file which is parsed into my template.
編輯:我想補充一點,當我最初將頁面加載到瀏覽器中時,它會成功加載我的 JSON 中的文本內容,但沒有任何樣式。當我查看源代碼時,鏈接也是正確的,這讓我感到困惑,為什么樣式表不適用,因為它位于可以訪問的正確目錄中。這是我在瀏覽器中選擇 view-source 時的來源:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic JSON Events</title>
<link rel="stylesheet" href="./jsofun.css"></style>
</head>
<body>
<section id="title">
<h1 id="text-title">Second Post Test</h1>
<time id="timestamp">
Friday, March 18th, 12:21AM
</time>
</section>
<nav role="navigation" id="site-nav">
<ul id="sitemap">
</ul>
</nav>
<main role="main" id="main">
This is my second post where I am able to use dynamic URL routing
</main>
<footer role="contentinfo" id="footer">
<section id="content-info" role="contentinfo">
This post was used primarily to test and layout how the rest of my posts will appear.
</section>
<form id="contact-form" role="form">
<address>
Contact me by <a id="my-email" href="mailto:[email protected]" class="my-email">e-mail</a>
</address>
</form>
</footer>
<script src="./jsofun.js">
</script>
</body>
</html>
作為參考,這是我的 JSON 檔案外觀的示例:
{
"title" : "Second Post Test",
"timestamp": "Friday, March 18th, 12:21AM",
"main": "This is my second post where I am able to use dynamic URL routing",
"content_info": "This post was used primarily to test and layout how the rest of my posts will appear."
}
uj5u.com熱心網友回復:
您的 Go 服務器設定為僅提供/blog/路徑,它通過執行blogHandler. 您的 Go 服務器中沒有其他任何東西被設定為提供諸如 css、js 或影像檔案之類的資產。
對于此類事情,您通常需要FileServer在單獨的路徑中注冊單獨的處理程式。例子:
func main() {
http.HandleFunc("/blog/", blogHandler)
// To serve a directory on disk (/path/to/assets/on/my/computer)
// under an alternate URL path (/assets/), use StripPrefix to
// modify the request URL's path before the FileServer sees it:
http.Handle("/assets/", http.StripPrefix("/assets/",
http.FileServer(http.Dir("/path/to/assets/on/my/computer"))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
您需要修復的另一件事是指向 HTML 中這些資產欄位的鏈接,它們應該是絕對的,而不是相對的。
...
<link rel="stylesheet" href="/assets/jsofun.css"></style>
...
<script src="/assets/jsofun.js">
當然,只有當資產位于/path/to/assets/on/my/computer目錄中時,上述內容才有效,例如
/path/to/assets/on/my/computer
├── jsofun.css
└── jsofun.js
您blogHandler不必要地為每個請求創建一個新檔案而不洗掉它,這有可能很快將您的磁盤填滿到其最大容量。要提供模板,您無需創建新檔案,而是可以直接將模板執行到http.ResposeWriter. 還建議只決議一次模板,尤其是在生產代碼中,以避免不必要的資源浪費:
type BlogPost struct {
Title string `json:"title"`
Timestamp string `json:"timestamp"`
Main string `json:"main"`
ContentInfo string `json:"content_info"`
}
var blogTemplate = template.Must(template.ParseFiles("./blogtemplate.html"))
func blogHandler(w http.ResponseWriter, r *http.Request) {
blogstr := r.URL.Path[len("/blog/"):] ".json"
f, err := os.Open(blogstr)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
defer f.Close()
var post BlogPost
if err := json.NewDecoder(f).Decode(&post); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := blogTemplate.Execute(w, post); err != nil {
log.Println(err)
}
}
uj5u.com熱心網友回復:
讓我們了解當您請求時會發生什么http://localhost:8000/blog/post#。
瀏覽器請求頁面;您的代碼成功構建并回傳一些html- 這將包括:
<link rel="stylesheet" href="./jsofun.css"></style>
瀏覽器接收并處理 HTML;作為該程序的一部分,它要求css上述內容。現在原始請求位于檔案夾中,/blog/post#因此./jsofun.css變為http://localhost:8000/blog/jsofun.css.
當你的 go 應用收到這個請求blogHandler時會被呼叫(由于請求路徑);它剝離/blog/然后添加.json以獲取檔案名jsofun.css.json。然后您嘗試打開此檔案并收到錯誤,因為它不存在。
有幾種方法可以解決這個問題;更改要使用的模板<link rel="stylesheet" href="/jsofun.css"></style>可能是一個開始(但我不知道jsofun.css存盤在哪里,并且您沒有顯示任何可以為該檔案提供服務的代碼)。我認為還值得注意的是,您不必index.html在磁盤上創建檔案(除非有其他原因這樣做)。
(有關其他問題和進一步的步驟,請參閱 mkopriva 的答案 - 在發布該答案時進入該答案的一半,并且覺得該演練可能仍然有用)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445762.html
上一篇:SpringBoot發送電子郵件,但Angular不發送。如何正確連接方法?
下一篇:Gogin-從本地瀏覽器獲取資料
