构建包含 firebase 凭证文件的 golang。json

Build golang including firebase credential file .json

我写了一个 Golang 程序,旨在解析一个 scv 文件并将数据上传到 FireStore,这个程序是为了与那些只写 scv 路径来上传信息的人分享的。

我正在使用它来使用 firebase-admin:

opt := option.WithCredentialsFile("path/to/serviceAccountKey.json")

这种方法在我这样做时效果很好:

$ go run main.go

但是当我构建项目并执行二进制文件时,我得到了这个:

$ cannot read credentials file: open firebase-config.json: no such file or directory 

我做了 但这意味着也要分享 firebase-config.json, 这个 Go 程序的想法只是共享可执行文件而没有任何其他文档。

有没有办法像这样直接使用 json 构建包含 json 的程序或验证 firebase-admin?:

opt := option.WithCredentials({< authentication json >})

我没有找到使用此方法的文档或示例 WithCredential

我不知道这是否是解决此问题的最佳方法,但我就是这样做的:

  1. 我决定将此脚本可执行文件放入 /opt/< dir-name >/bin
  2. 我写了一个额外的函数来创建 auth .json /opt/< dir-name >/auth.json
  3. 所有脚本使用此 /opt/< dir-name >/auth.json 文件执行
  4. 我写了另一个函数,它在执行结束时删除 auth.json

所以,现在我可以这样做了:

var file string = "/opt/< dir-name >/auth.json" 
sa := option.WithCredentialsFile(file)

现在我可以使用指令 "Install into /opt/< dir-name>/bin and add this to your $PATH"

共享此脚本

对我来说,我使用 $GOPATH 来解决这个问题

  1. 例如我的$GOPATH是/home/Frank/work
  2. 我把我的 .json 文件放在 /home/Frank/work/myfile.json
  3. 我把代码改成

    opt := option.WithCredentialsFile("/home/Frank/work/myfile.json")

不知何故它起作用了。 :D

当我试图将我用 Node 编写的 Google 云函数移动到 Google 云 运行 时,我 运行 遇到了 firebase-admin 这个确切的问题( GCR) 使用 Go。具体来说,错误 Error initializing app: cannot read credentials file: open ./firebase.json: no such file or directory

我不确定为什么,但是当我将我的容器推送到 GCR 时,JSON 文件丢失了,我无法连接到 firebase-admin。我猜这很像你说的,从理论上讲,Go 程序应该是独立的。

我相信我找到了适合我需要的解决方案,希望对您有所帮助。

opt := option.WithCredentialsJSON([]byte(`{"some": "json"}`))

这确实意味着将一个 JSON 文件推入一个字符串中,这绝对不应该在所有情况下都有效。然而,由于 firebase.json 文件通常有多小,对于这个用例 IMO 应该没问题。

引导我走这条路的链接,留在最后以防这些链接更改或中断: