在我看了this video后,我自己尝试了。但是,我收到了恐慌错误panic: open templates/index.html: The system cannot find the path specified.
完整错误消息如下所示。
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
,{{1} } ...但我得到了同样的错误信息。
以下是go程序(1.3_UsingTemplate.go)。
bin
文件结构
要解决此问题,我需要先将当前工作目录更改为包含* .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))
}
。在GoClipse中,是否可以将任何设置设置为go run {filename.go}
以自动将当前工作目录更改为包含* .go文件的文件夹?
答案 0 :(得分:2)
您指定了相对于当前工作目录的路径。此目录可能与包含源代码的目录没有任何关系。
Change directory到E:/Users/User/Desktop/codespace/go_workspace/src/go-for-web-dev/src
运行您的程序。模板的路径是相对于此目录的。
答案 1 :(得分:2)
os.Getwd()
可用于返回项目的根工作目录,然后与模板文件的内部路径连接:
// Working Directory
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
// Template
tpl, err := template.ParseFiles(wd + "/templates/index.html")
答案 2 :(得分:0)
查看您的目录结构我认为您的示例中有拼写错误。你应该使用
templates := template.Must(template.ParseFiles("templates/index.html"))
而不是
templates := template.Must(template.ParseFiles("template/index.html"))
请注意templates
末尾的“s”。
如果仍然无法正常工作,则应使用os.Getwd
获取与当前目录对应的根路径名称。
templates := template.Must(template.ParseFiles(os.Getwd("templates/index.html")))