【问题标题】:template parsing error - "operation not permitted"模板解析错误 - “不允许操作”
【发布时间】:2014-07-30 15:25:05
【问题描述】:

我正在开发一个 Google App Engine Go 应用程序,并且需要在我的一个包中使用一些 HTML 模板。当前文件结构为:

GOPATH/github.com/NAME/PROJECT/
                               app/
                                   app.go
                                   app.yaml
                               package/
                                       package.go
                                       Templates/
                                                 Template.html

为了包含这个包,我使用:

导入“github.com/NAME/PROJECT/package”

在 package.go 内部,我尝试以各种方式解析我的 Template.html 文件:

//Template, err := template.ParseFiles("package/Templates/Template.html") //doesn't work - "The system cannot find the path specified."
//Template, err := template.ParseFiles("github.com/NAME/PROJECT/package/Templates/Template.html") //doesn't work - "The system cannot find the path specified."
//Template, err := template.ParseFiles("Templates/Template.html") //doesn't work - "The system cannot find the path specified."
//Template, err := template.ParseFiles("/Templates/Template.html") //doesn't work - "The system cannot find the path specified."
Template, err := template.ParseFiles("../package/Templates/Template.html") //works on desktop!

所以我选择了适用于我的桌面测试环境的最后一个选项,将其上传到 AppEngine,然后我收到“不允许操作”的新错误...

如何解析具有如上所示文件配置的 HTML 模板,该模板既适用于 App Engine,也适用于桌面?

【问题讨论】:

    标签: html google-app-engine templates path go


    【解决方案1】:

    您需要将app.yaml 放在应用程序的根目录中。 App Engine 使用app.yaml 的位置来确定哪些文件与您的应用程序相关联。您想将此文件移至顶层。

    例如,假设我们有类似的东西:

    app.go
    app.yaml
    templates/t1
    templates/t2
    

    app.yaml 是您的应用程序通常拥有的,app.go 是:

    package app
    
    import (
        "html/template"
        "net/http"
    )
    
    var templates = template.Must(template.ParseGlob("templates/*"))
    
    func init() {
        http.HandleFunc("/", rootHandler)
    }
    
    func rootHandler(w http.ResponseWriter, r *http.Request) {
        name := r.URL.Path[1:]    // drop the leading slash
        tmpl := templates.Lookup(name)
        if tmpl == nil {
            http.NotFound(w, r)
            return
        }
        tmpl.Execute(w, nil)
    }
    

    和templates/t1 和templates/t2 是合适的模板文件。然后,一旦我们有了这个,我们就可以在生成的 webapp 中访问 t1/ 和 t2/,它应该可以在 App Engine 上正常运行和部署。

    关键是将app.yaml 放在应用程序的顶级目录中。要记住的另一个警告:确保您尝试从动态应用程序中读取的任何文件都不是静态提供或跳过的。检查您的app.yaml。如果要静态提供文件,则通常只允许前端查看该文件,这意味着您的后端不会。并且在部署过程中会完全忽略跳过的文件。

    【讨论】:

    • 感谢您对静态服务文件的评论 - 这是我的问题。
    【解决方案2】:

    您无法从 GAE 中的目录中读取。要么将模板嵌入到 go 文件中,要么使用 google Blob Storage API。 https://developers.google.com/appengine/docs/go/blobstore/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2021-11-18
    • 2012-06-11
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多