无法在 golang 中提供静态 html 文件

我正在尝试学习有关 golang 的在线视频课程,但在提供静态 html 文件时出现错误。


package main


import (

    "io/ioutil"

    "net/http"

)


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)))

    }

}

我的文件夹结构 是这样的。


心有法竹
浏览 210回答 2
2回答

智慧大石

正确的路径是 ../../public,因为您的 main.go 文件在 main/src 文件夹中。

皈依舞

根据指向您的文件夹结构的链接,我猜您需要path := "../public/" + req.URL.Path. 您的应用程序正在从该bin目录运行,因此您无法直接进入同级目录,您需要..退出一个目录,此时public实际上是一种选择。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go