猿问

如何防止 http.ListenAndServe 改变静态输出中的样式属性?

在一个非常基本的手写网页(没有 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 title

func 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.html

func controlPage(w http.ResponseWriter, r *http.Request) {

    p, _ := loadPage("controlpage")

    fmt.Fprintf(w, string(p))

}                                    

在上面的func 中loadPage(),info是一个日志记录调用。对于调试,我在返回controlpage.html. 日志条目显示它在那个时候没有被破坏,所以问题几乎必须在 ListenAndServe 中。


我在 Go 文档中找不到任何http似乎适用的内容。我不知道这里发生了什么。任何帮助表示赞赏。


白衣非少年
浏览 146回答 3
3回答

紫衣仙女

您的代码存在几个问题(包括当您可以用来提供静态内容时它完全存在的事实,以及您在将其发回而不是流式传输之前http.FileServer将整个响应读入 a 的事实)但主要问题是这:[]bytefmt.Fprintf(w, string(p))Fprintf的第一个参数是格式字符串。替换格式字符串中开头的内容%就是它的作用。要将 a 写给[]bytewriter,您不需要 fmt 包,因为您不想格式化任何东西。w.Write()就足够了。fmt.Fprint也可用但完全没有必要;它会做一些无意义的额外工作,然后调用w.Write.

波斯汪

问题是fmt.Fprintf将响应主体解释为带有 % 替换的格式字符串。解决此问题的一种方法是提供格式字符串:fmt.Fprintf(w,&nbsp;"%s",&nbsp;p)使用这种方法不需要转换p为字符串。这里的目标是将字节写入响应编写器。将字节写入响应编写器(或任何其他 io.Writer)的惯用且最有效的方法是:w.Write(p)该fmt包不适合在这里使用,因为不需要格式化。

红糖糍粑

你能试试这个吗,注意Fprint而不是Fprintffunc&nbsp;controlPage(w&nbsp;http.ResponseWriter,&nbsp;r&nbsp;*http.Request)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;p,&nbsp;_&nbsp;:=&nbsp;loadPage("controlpage") &nbsp;&nbsp;&nbsp;&nbsp;fmt.Fprint(w,&nbsp;string(p)) }
随时随地看视频慕课网APP

相关分类

Go
我要回答