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

如何在 Go 语言中指定 `template.ParseFiles` 的文件位置?

如何在 Go 语言中指定 `template.ParseFiles` 的文件位置?

Go
德玛西亚99 2022-01-10 17:23:23
看完这个视频,我自己试试。但是,我收到恐慌错误panic: open templates/index.html: The system cannot find the path specified.Complete erroe 消息如下所示。Hello, Go Web Development 1.3panic: open templates/index.html: The system cannot find the path specified.goroutine 1 [running]:panic(0x789260, 0xc082054e40)    F:/Go/src/runtime/panic.go:481 +0x3f4html/template.Must(0x0, 0xe34538, 0xc082054e40, 0x0)    F:/Go/src/html/template/template.go:340 +0x52main.main()    E:/Users/User/Desktop/codespace/go_workspace/src/go-for-web-dev/src/1.3_UsingTemplate.go:11 +0x20d我尝试了不同的字符串,例如"templates/index.html", "index.html", "./template/index.html"... 另外,我尝试将整个模板文件夹复制到pkg, bin...但我收到相同的错误消息。以下是go程序(1.3_UsingTemplate.go)。package srcimport (    "fmt"    "net/http"    "html/template")func main() {    fmt.Println("Hello, Go Web Development 1.3")    templates := template.Must(template.ParseFiles("templates/index.html"))  //This line should have some problem    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {            http.Error(w, err.Error(), http.StatusInternalServerError)        }    })    fmt.Println(http.ListenAndServe(":8080",nil))}文件结构更新为了解决这个问题,我需要先将当前工作目录更改为包含 *.go 文件的文件夹。然后,执行go run {filename.go}. 在 GoClipse 中,是否有任何设置可以设置Run Configurations为自动将当前工作目录更改为包含 *.go 文件的文件夹?
查看完整描述

2 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

您指定了相对于当前工作目录的路径。该目录可能与包含源代码的目录没有任何关系。

更改目录E:/Users/User/Desktop/codespace/go_workspace/src/go-for-web-dev/src运行您的程序。模板的路径是相对于这个目录的。


查看完整回答
反对 回复 2022-01-10
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

os.Getwd() 可用于返回项目的根工作目录,然后与模板文件的内部路径连接:


// Working Directory

wd, err := os.Getwd()

if err != nil {

   log.Fatal(err)

}

// Template

tpl, err := template.ParseFiles(wd + "/templates/index.html")


查看完整回答
反对 回复 2022-01-10
  • 2 回答
  • 0 关注
  • 531 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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