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

Mik*_*lis -5 http go

在一个非常基本的手写网页(没有js,样式表等)中,我有一些静态html,其部分看起来像这样。

<li style="font-size:200%; margin-bottom:3vh;">
  <a href="http://192.168.1.122:8000">
    Reload HMI
  </a>
</li>
Run Code Online (Sandbox Code Playgroud)

我正在使用Go的http.ListenAndServe服务该页面。出现的内容如下所示:

<li style="font-size:200%!;(MISSING) margin-bottom:3vh;">
  <a href="http://192.168.1.122:8000">
    Reload HMI
  </a>
</li>
Run Code Online (Sandbox Code Playgroud)

请注意更改的样式属性。

服务器实施也是基本的。它作为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))
}                                    
Run Code Online (Sandbox Code Playgroud)

loadPage()上面的func中,info是一个日志记录调用。对于调试,我只是在返回的内容之前调用它controlpage.html。日志条目显示当时还没有被处理,因此问题几乎必须在ListenAndServe内。

我在Go文档中找不到任何http适用的内容。我不知道这是怎么回事。任何帮助表示赞赏。

hob*_*bbs 5

您的代码有几个问题(包括当您可以http.FileServer用来提供静态内容时根本就存在的事实,以及在将整个响应[]byte发送回而不是流式传输之前将整个响应读入一个的事实),但主要的问题是这个:

fmt.Fprintf(w, string(p))
Run Code Online (Sandbox Code Playgroud)

Fprintf第一个参数是格式字符串。用开头的格式字符串替换内容%就是它的作用。要写给写[]byte作者,您不需要fmt包,因为您不想格式化任何东西。w.Write()足够好。fmt.Fprint也可用,但完全不必要;它将做多余的工作,等于一无所有,然后致电w.Write

  • @MikeEllis根据nvcnvn的答案进行了更新,该答案通过忽略问题,提出不正确的建议以及无法解释建议背后的任何原因而给OP造成了三重损害,只是提供了没有解释的代码。 (6认同)