【问题标题】:panic: open templates/base.html: The system cannot find the path specified恐慌:打开模板/base.html:系统找不到指定的路径
【发布时间】:2013-06-14 05:24:21
【问题描述】:

通过 shadynasty.biz/blog/2012/07/30/quick-and-clean-in-go 链接,我正在尝试在 Go 编程中创建模板。我的项目结构是使用 Go-SDK 谷歌应用引擎创建的。 google_appengine/myapp/hello/hello.go 文件存在,那么在哪里创建模板文件夹?我在 "hello" 文件夹中创建了 "template" 文件夹,但出现错误 "panic: open templates/base.html: The system cannot find the path specified" 并且服务器停止运行。可以做什么?

【问题讨论】:

  • 例如: package main import( "fmt" "net/http" "html/template" ) var index = template.Must(template.ParseFiles( "/templates/base.html", " /templates/index.html", )) func handler(w http.ResponseWriter, r *http.Request) { if err := index.Execute(w, nil); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } fmt.Fprint(w, "hello", "\n") } func init() { http.HandleFunc("/" , 处理程序) }

标签: google-app-engine go


【解决方案1】:

实际上,您确实可以访问您放入应用程序文件夹的几乎所有文件。

您可以使用 ioutil 来读取文件: http://golang.org/pkg/io/ioutil/#ReadFile

还有一点需要注意,app.yaml中只能读取静态处理程序未指定的文件。

因此,请将模板文件保存在一个文件夹中,将静态和直接提供的文件保存在另一个文件夹中。

【讨论】:

  • app.yaml中如何指定要上传的模板文件?
【解决方案2】:

只有在您从字段中传递 html 时才能在 appengine 上使用模板,因为 appengine 规则您无权访问文件系统

这是一个例子

const loginTemplateHTML = `<html>
  <body>
    <form action="/login" method="post">
      <div><input name="username" type="text" /></div>
      <div><input name="password" type="password" /></div>
      <div><input type="submit" value="login"></div>
    </form>
  </body>
</html>
    `    
var loginTemplate = template.Must(template.New("Login").Parse(loginTemplateHTML))

func login (w http.ResponseWriter, r *http.Request) {
    if err := loginTemplate.Execute(w,nil); err != nil {
         http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

【讨论】:

  • 谢谢。我们可以用“模板”方法做同样的事情吗?使用shadynasty.biz/blog/2012/07/30/quick-and-clean-in-go 链接我正在尝试该示例,但它给出了“恐慌:打开模板/base.html:系统找不到指定的路径”这个错误。我应该在哪里放置“模板”文件夹?目录是 google_appengine/myapp/hello/hello.go 和 google_appengine/myapp/hello/templates/base.html 和 index.html 示例: var index = template.Must(template.ParseFiles( "templates/_base.html", "templates /index.html", ))
  • 遗憾的是,在 appengine 上,您不能使用文件夹中的模板,您必须将它们作为 const 或 var 放入代码中但是如果您只是从链接中完成完整示例,我想您必须将模板文件夹放在 myapp 目录下
  • 好的。现在可以从模板中查看基本内容。谢谢
【解决方案3】:

问题是应用引擎不会像 go run hello.go 那样调用您的应用程序。它从根目录调用 go run google_appengine/myapp/hello/hello.go。您有两种解决方案来解决此问题。

  1. 重新定义要从根目录调用的路径。

我推荐和验证的作品只是设置添加从项目根目录到模板文件夹的路径。例如,如果项目的根目录是 myRepo/,而 webapp 的路径是 /myRepo/webapp/hello.go,那么模板现在位于 webapp/templates/index.html 而不是 templates/index.html。为了调用它类似于应用程序引擎,您将从根目录调用它。去运行 webapp/main.go。

  1. 在 app.yaml 中定义自定义入口点。

我尚未验证此解决方案,但我认为它会起作用。在app.yaml中有一个entrypoint命令是用来启动代码的命令。

入口点:cd myRepo/webapp/ && go run main.go

这里是 app.yaml 的文档。确保为您的静态目录添加 url。

https://cloud.google.com/appengine/docs/standard/go/config/appref

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2018-12-12
    • 2016-04-23
    • 2017-01-04
    • 2014-04-24
    相关资源
    最近更新 更多