dongleiqiao4906 2016-07-07 06:27
浏览 134
已采纳

Golang中没有这样的文件或目录错误

I want to specify an html template in one of my golang controller My directory structure is like this

 Project
 -com
  -src
   - controller
     -contoller.go
 -view
  - html
   -first.html

I want to load first.html for request /new .I have used NewHandler for url /new and the NewHandler func is executing when /new request comes and is in controller.go. Here is my code

func NewHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("view/html/first.html")
    if err == nil {
        log.Println("Template parsed successfully....")
    }
 err := templates.ExecuteTemplate(w, "view/html/first.html", nil)
if err != nil {
    log.Println("Not Found template")
}
//  t.Execute(w, "")
}

But I am getting an error

     panic: open first.html: no such file or directory

Please help me to remove this error. Thanks in advance

  • 写回答

3条回答 默认 最新

  • douwenpin0428 2016-07-07 08:35
    关注

    I have solved the issue by giving absolute path of the html. For that I created a class in which the html are parsed

    package htmltemplates
    
    import (
    "html/template"
    "path/filepath"
    )
    

    And in the NewHandler method I removed //Templates is used to store all Templates var Templates *template.Template

    func init() {
    filePrefix, _ := filepath.Abs("./work/src/Project/view/html/")       // path from the working directory
    Templates = template.Must(template.ParseFiles(filePrefix + "/first.html")) 
    ...
    //htmls must be specified here to parse it
    }
    

    And in the NewHandler I removed first 5 lines and instead gave

    err := htmltemplates.Templates.ExecuteTemplate(w, "first.html", nil)
    

    It is now working .But need a better solution if any

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?