2014-06-10 40 views
1

我正在開發一個Google App Engine Go應用程序,並且需要在我的一個包中使用一些HTML模板。當前文件的結構是:GAE Golang模板解析錯誤 - 「操作不允許」

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,也適用於桌面?

回答

-1

您無法從GAE中的目錄讀取數據。無論是將模板嵌入到go文件中,還是使用Google Blob存儲API。 https://developers.google.com/appengine/docs/go/blobstore/

+0

...以下是使用go.rice將模板嵌入二進制文件的示例:https://github.com/drone/drone/blob/master/pkg/template/template.go#L34-L37 – elithrar

+2

這在技術上是錯誤的。請參閱:https://cloud.google.com/appengine/docs/go/#Go_The_sandbox;閱讀文件是完全合法的。被禁止的是試圖讀取不屬於應用程序的文件。這個問題提供了一個場景,其中有一個'app /'目錄,但模板不是'app /'的子目錄!因此,應用程序無法訪問模板文件,因爲它們不屬於應用程序的一部分。 – dyoo

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/t1templates/t2是合適的模板文件。然後,一旦我們有了這個,我們可以在產生的webapp中訪問t1/t2/,它應該在App Engine上提供服務和部署。

關鍵是要在您的應用程序的頂級目錄中有app.yaml。另外需要注意的一點是:確保您試圖從動態應用程序中讀取的任何文件不會被靜態提供或跳過。檢查您的app.yaml。如果一個文件被靜態地提供,則通常只有前端被允許看到文件,這意味着你的後端不會。在部署期間,跳過的文件完全被忽略。