亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何防止 http.ListenAndServe 改變靜態輸出中的樣式屬性?

如何防止 http.ListenAndServe 改變靜態輸出中的樣式屬性?

Go
白衣非少年 2023-06-12 18:23:12
在一個非常基本的手寫網頁(沒有 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 寫給[]bytewriter,您不需要 fmt 包,因為您不想格式化任何東西。w.Write()就足夠了。fmt.Fprint也可用但完全沒有必要;它會做一些無意義的額外工作,然后調用w.Write.


查看完整回答
反對 回復 2023-06-12
?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

問題是fmt.Fprintf將響應主體解釋為帶有 % 替換的格式字符串。解決此問題的一種方法是提供格式字符串:

fmt.Fprintf(w, "%s", p)

使用這種方法不需要轉換p為字符串。

這里的目標是將字節寫入響應編寫器。將字節寫入響應編寫器(或任何其他 io.Writer)的慣用且最有效的方法是:

w.Write(p)

fmt包不適合在這里使用,因為不需要格式化。


查看完整回答
反對 回復 2023-06-12
?
紅糖糍粑

TA貢獻1815條經驗 獲得超6個贊

你能試試這個嗎,注意Fprint而不是Fprintf

func controlPage(w http.ResponseWriter, r *http.Request) {
    p, _ := loadPage("controlpage")
    fmt.Fprint(w, string(p))
}


查看完整回答
反對 回復 2023-06-12
  • 3 回答
  • 0 關注
  • 206 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號