我在 Go 中創(chuàng)建了一個(gè)服務(wù)器,我正在嘗試在瀏覽器中運(yùn)行一個(gè) html 文件。但是瀏覽器只是像 txt 文件一樣打印出代碼,而不是呈現(xiàn) html 格式。我的 index.html 文件保存在 /public 目錄中。我的 Go 代碼如下所示:package mainimport ( "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))) }}
3 回答

海綿寶寶撒
TA貢獻(xiàn)1809條經(jīng)驗(yàn) 獲得超8個(gè)贊
在您的主要嘗試中,使用http.HandleFunc("/", ServeHTTP)
then 編輯ServeHTTP
方法,使其沒(méi)有接收器,即;func ServeHTTP(w http.ResponseWriter, req *http.Request)
您嘗試使用該對(duì)象,該Handle
方法也可能工作正常(如果正確實(shí)施),但大多數(shù)示例都使用HandleFunc
,如果您這樣做,我敢打賭您的問(wèn)題會(huì)消失。
唯一會(huì)導(dǎo)致您觀察到的問(wèn)題的另一件事是無(wú)法讀取內(nèi)容分配給的文件,data
或者對(duì)該文件中的數(shù)據(jù)實(shí)際存在一些誤解。
- 3 回答
- 0 關(guān)注
- 276 瀏覽
添加回答
舉報(bào)
0/150
提交
取消