go - golang中没有这样的文件或目录错误

标签 go

我想在我的一个 golang Controller 中指定一个 html 模板 我的目录结构是这样的

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

我想为请求/new 加载 first.html。我已经将 NewHandler 用于 url/new,并且当/new 请求出现并且在 controller.go 中时,NewHandler 函数正在执行。这是我的代码

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

但是我遇到了一个错误

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

请帮我消除这个错误。提前致谢

最佳答案

我已经通过提供 html 的绝对路径解决了这个问题。为此,我创建了一个解析 html 的类

package htmltemplates

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

在我删除的 NewHandler 方法中 //Templates用于存放所有的Templates var 模板 *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
}

在 NewHandler 中,我删除了前 5 行,而是给出了

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

它现在正在工作。但如果有的话需要更好的解决方案

关于go - golang中没有这样的文件或目录错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38238764/

相关文章:

go - 这两段 Go 代码是否等价?

go - db.First() 不使用主键名

dictionary - 构造深层结构不起作用

go - 在 http 中提供 zip 文件中的内容

go - YAML 修改别名序列元素

string - 如何在Go中获取所有ASCII字符?

具有不同超时的 Golang goroutine-safe http 客户端?

go - 在 Echo 框架中测试多部分表单上传端点

go - 两种不同语言之间的 Protocol Buffer

for-loop - 从 3 个单独的 slice (每个结构属性一个 slice )创建新的组合结构 slice 时索引超出范围