为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
心有法竹 2021-12-27 16:04:14
我正在尝试学习有关 golang 的在线视频课程,但在提供静态 html 文件时出现错误。package mainimport (    "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)))    }}我的文件夹结构 是这样的。
查看完整描述

2 回答

?
智慧大石

TA贡献1946条经验 获得超3个赞

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


查看完整回答
反对 回复 2021-12-27
?
皈依舞

TA贡献1851条经验 获得超3个赞

根据指向您的文件夹结构的链接,我猜您需要path := "../public/" + req.URL.Path. 您的应用程序正在从该bin目录运行,因此您无法直接进入同级目录,您需要..退出一个目录,此时public实际上是一种选择。


查看完整回答
反对 回复 2021-12-27
  • 2 回答
  • 0 关注
  • 209 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号