在一個非常基本的手寫網頁(沒有 js、樣式表等)中,我有一些靜態 html,其中有一個部分看起來像這樣。<li style="font-size:200%; margin-bottom:3vh;"> <a href="http://192.168.1.122:8000"> Reload HMI </a></li>我正在使用 Go 的 http.ListenAndServe 來提供頁面。結果是這樣的:<li style="font-size:200%!;(MISSING) margin-bottom:3vh;"> <a href="http://192.168.1.122:8000"> Reload HMI </a></li>請注意更改后的樣式屬性。服務器實現也很初級。它作為 goroutine 啟動:// systemControlService provides pages on localhost:8003 that// allow reboots, shutdowns and restoring configurations.func systemControlService() { info("Launching system control service") http.HandleFunc("/", controlPage) log.Fatal(http.ListenAndServe(":8003", nil))}// loadPage serves the page named by titlefunc loadPage(title string) ([]byte, error) { filename := "__html__/" + title + ".html" info(filename + " requested") content, err := ioutil.ReadFile(filename) if err != nil { info(fmt.Sprintf("error reading file: %v", err)) return nil, err } info(string(content)) return content, nil}// controlPage serves controlpage.htmlfunc controlPage(w http.ResponseWriter, r *http.Request) { p, _ := loadPage("controlpage") fmt.Fprintf(w, string(p))} 在上面的func 中loadPage(),info是一個日志記錄調用。對于調試,我在返回controlpage.html. 日志條目顯示它在那個時候沒有被破壞,所以問題幾乎必須在 ListenAndServe 中。我在 Go 文檔中找不到任何http似乎適用的內容。我不知道這里發生了什么。任何幫助表示贊賞。
3 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
您的代碼存在幾個問題(包括當您可以用來提供靜態內容時它完全存在的事實,以及您在將其發回而不是流式傳輸之前http.FileServer
將整個響應讀入 a 的事實)但主要問題是這:[]byte
fmt.Fprintf(w,?string(p))
Fprintf
的第一個參數是格式字符串。替換格式字符串中開頭的內容%
就是它的作用。要將 a 寫給[]byte
writer,您不需要 fmt 包,因為您不想格式化任何東西。w.Write()就足夠了。fmt.Fprint
也可用但完全沒有必要;它會做一些無意義的額外工作,然后調用w.Write
.

波斯汪
TA貢獻1811條經驗 獲得超4個贊
問題是fmt.Fprintf
將響應主體解釋為帶有 % 替換的格式字符串。解決此問題的一種方法是提供格式字符串:
fmt.Fprintf(w, "%s", p)
使用這種方法不需要轉換p
為字符串。
這里的目標是將字節寫入響應編寫器。將字節寫入響應編寫器(或任何其他 io.Writer)的慣用且最有效的方法是:
w.Write(p)
該fmt
包不適合在這里使用,因為不需要格式化。

紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
你能試試這個嗎,注意Fprint而不是Fprintf
func controlPage(w http.ResponseWriter, r *http.Request) { p, _ := loadPage("controlpage") fmt.Fprint(w, string(p)) }
- 3 回答
- 0 關注
- 206 瀏覽
添加回答
舉報
0/150
提交
取消