dtwy2858 2016-05-19 16:15
浏览 1531

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

After I watched this video, I try it myself. However, I get the panic error panic: open templates/index.html: The system cannot find the path specified. The Complete erroe message is like the following.

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

I have tried different string like "templates/index.html", "index.html", "./template/index.html"... Also, I try to copy the entire template folder into pkg, bin...But I get the same error message.

The following is the go program (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))
}

File Structure

enter image description here


Update

To solve this problem, I need to first change the current working directory to the folder containing the *.go file. Then, execute go run {filename.go}. In GoClipse, is there any setting can be set to the Run Configurations for automatically changing the current working directory to the folder containing the *.go file?

  • 写回答

2条回答 默认 最新

  • duannaikuang1301 2016-05-19 16:30
    关注

    You specified a path relative to the current working directory. This directory may not have any relationship with the directory containing the source code.

    Change directory to E:/Users/User/Desktop/codespace/go_workspace/src/go-for-web-dev/src to run your program. The path to the template is relative to this directory.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看