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

看完这个视频,我自己试试。但是,我收到恐慌错误panic: open templates/index.html: The system cannot find the path specified.Complete erroe 消息如下所示。


Hello, Go Web Development 1.3

panic: open templates/index.html: The system cannot find the path specified.


goroutine 1 [running]:

panic(0x789260, 0xc082054e40)

    F:/Go/src/runtime/panic.go:481 +0x3f4

html/template.Must(0x0, 0xe34538, 0xc082054e40, 0x0)

    F:/Go/src/html/template/template.go:340 +0x52

main.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 src


import (

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

}

文件结构

http://img3.mukewang.com/61dbfb23000172c402850335.jpg

更新

为了解决这个问题,我需要先将当前工作目录更改为包含 *.go 文件的文件夹。然后,执行go run {filename.go}. 在 GoClipse 中,是否有任何设置可以设置Run Configurations为自动将当前工作目录更改为包含 *.go 文件的文件夹?


德玛西亚99
浏览 532回答 2
2回答

慕村9548890

您指定了相对于当前工作目录的路径。该目录可能与包含源代码的目录没有任何关系。更改目录以E:/Users/User/Desktop/codespace/go_workspace/src/go-for-web-dev/src运行您的程序。模板的路径是相对于这个目录的。

拉风的咖菲猫

os.Getwd() 可用于返回项目的根工作目录,然后与模板文件的内部路径连接:// Working Directorywd, err := os.Getwd()if err != nil {   log.Fatal(err)}// Templatetpl, err := template.ParseFiles(wd + "/templates/index.html")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go