【发布时间】:2015-09-20 14:52:44
【问题描述】:
我在 Go 中创建了一个服务器,并尝试在浏览器中运行一个 html 文件。但是浏览器只是像 txt 文件一样打印出代码,而不是呈现 html 格式。我的 index.html 文件保存在 /public 目录中。
我的 go 代码如下所示:
package main
import (
"net/http"
"io/ioutil"
)
func main() {
http.Handle("/", new(MyHandler))
http.ListenAndServe(":8000", nil)
}
type MyHandler struct {
http.Handler
}
func (this *MyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
path := "public/" + req.URL.Path
data, err := ioutil.ReadFile(string(path))
if err == nil {
w.Write(data)
} else {
w.WriteHeader(404)
w.Write([]byte("404 - " + http.StatusText(404)))
}
}
【问题讨论】:
-
请在此行之后显示您希望
data保持的值;data, err := ioutil.ReadFile(string(path)). -
您几乎没有发送任何标头(只有 http 包添加的绝对最小值)。这是不好的。如果您希望您的浏览器处理您作为 HTML 发送的数据,您应该告诉他:将 Content-Type 标头设置为例如“文本/html”。