看完这个视频,我自己试试。但是,我收到恐慌错误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 回答

拉风的咖菲猫
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")
- 2 回答
- 0 关注
- 531 浏览
添加回答
举报
0/150
提交
取消