如何在Go Server应用程序中配置凭据文件以使用Firebase模拟器

问题描述

我在Google App Engine上有一个服务器Go应用程序,该应用程序使用Firebase Auth和Firestore。

func InitFirebase() {
    ctx := context.Background()
    opt := option.WithCredentialsFile("keys/firebase.json")
    app,err := firebase.NewApp(ctx,nil,opt)
    if err != nil {
        panic(err)
    }
    FirebaseAuth,err = app.Auth(ctx)
    if err != nil {
        panic(err)
    }
    Firestore,err = app.Firestore(ctx)
    if err != nil {
        panic(err)
    }
}

它具有用于访问所有Firebase服务的json配置文件。 firebase.json是从Firebase控制台下载的,其中包含连接服务所需的所有参数:

{
  "type": "service_account","project_id": "xxxx","private_key_id": "xxxxx","private_key": "-----BEGIN PRIVATE KEY----- xxxxx \n-----END PRIVATE KEY-----\n","client_email": "xxxx.gserviceaccount.com","client_id": "xxxx","auth_uri": "https://accounts.google.com/o/oauth2/auth","token_uri": "https://oauth2.googleapis.com/token","auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs","client_x509_cert_url": "https://www.googleapis.com/robot/v1/Metadata/x509/firebase-adminxxxx.iam.gserviceaccount.com"
}

要连接到Firebase Firestore Emulator并维护身份验证,我必须输入什么值?

解决方法

不需要更改json文件。

仅定义环境变量FIRESTORE_EMULATOR_HOST =“ localhost:8080” ,才会自动完成与仿真器的连接。

如果使用的是Visual Studio Code,请在launch.json文件中定义它:

 "configurations": [
    {
        "name": "Launch","type": "go","request": "launch","mode": "auto","program": "${fileDirname}","env": {
            "FIRESTORE_EMULATOR_HOST": "localhost:8080"
        },"args": []
    }
]