【问题标题】:Google App Engine is not finding files in go runtimeGoogle App Engine 在运行时找不到文件
【发布时间】:2019-10-31 12:44:48
【问题描述】:

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

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

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 路径的切片。

【问题讨论】:

    标签: google-app-engine go google-cloud-platform


    【解决方案1】:

    函数runtime.Caller()返回编译时源文件路径。应用程序未在与其编译所在的目录相同的目录中运行。

    应用程序运行时将当前工作目录设置为包含 app.yaml 的目录。使用此函数获取模板目录:

    func getTemplatesDir() string {
        return "templates"
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-08
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 2016-04-04
      • 2023-03-25
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多