为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
猛跑小猪 2023-06-26 16:31:56
添加 go.mod 文件后,我无法从 App Engine 上的 golang 访问 HTML 模板文件。一切都在本地进行。我已使用 Stackdriver Debug 验证 App Engine 上是否存在 HTML 文件,但运行时看不到它们。这是我的代码。var templates map[string]*htmltpl.Templatefunc 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: go111main: ./mainhandlers:  - 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。
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

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

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

func getTemplatesDir() string {
    return "templates"
    }


查看完整回答
反对 回复 2023-06-26
  • 1 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信