Google App Engine 在 go 运行时找不到文件

添加 go.mod 文件后,我无法从 App Engine 上的 golang 访问 HTML 模板文件。一切都在本地进行。


我已使用 Stackdriver Debug 验证 App Engine 上是否存在 HTML 文件,但运行时看不到它们。这是我的代码。


var templates map[string]*htmltpl.Template


func init() {

    if templates == nil {

        templates = make(map[string]*htmltpl.Template)

    }


    templatesDir := getTemplatesDir()


    layouts, err := filepath.Glob(templatesDir + "/layouts/*.html")

    if err != nil {

        panic(err)

    }


    includes, err := filepath.Glob(templatesDir + "/includes/*.html")

    if err != nil {

        panic(err)

    }


    // Generate our templates map from our layouts/ and includes/ directories

    for _, layout := range layouts {

        files := append(includes, layout)

        templates[filepath.Base(layout)] = htmltpl.Must(htmltpl.ParseFiles(files...))

    }

}


func getTemplatesDir() string {

    _, filename, _, ok := runtime.Caller(1)

    if !ok {

        panic("Could not get filename")

    }

    dirpath := path.Join(path.Dir(filename), "../../templates")

    return dirpath

}


这是我的app.yaml:


runtime: go111


main: ./main


handlers:

  - url: .*

    script: auto

    secure: always

这是我的目录结构:


.

├── app.yaml

├── db/

├── go.mod

├── go.sum

├── handlers/

├── main

│   └── main.go

├── middleware/

├── models/

├── static/

├── templates/

│   ├── includes

│   │   ├── base.html

│   │   ├── button.html

│   │   ├── message.html

│   │   └── profile.html

│   └── layouts

│       └── thread.html

└── utils

    └── template

        └── template.go

我不明白为什么在 App Engine 上,调用filepath.Glob(templatesDir + "/layouts/*.html")返回一个空切片,而它返回一个包含本地运行时的路径的切片thread.html。


猛跑小猪
浏览 86回答 1
1回答

鸿蒙传说

该函数runtime.Caller()返回编译时源文件路径。该应用程序未在与其编译的目录相同的目录中运行。应用程序运行时当前工作目录设置为包含 app.yaml 的目录。使用此函数获取模板目录:func getTemplatesDir() string {     return "templates"     }
打开App,查看更多内容
随时随地看视频慕课网APP