我是GO的新手,我需要在整个应用程序中重用数据存储客户端,而不是为每个API调用一次又一次地创建它。我创建了一个db包,并在其中我将客户端存储在全局db变量中,以通过GetDB()函数重用它。但我得到以下错误
PermissionDenied desc =权限丢失或不足。
下面是我的数据库包代码
package db
import (
"context"
"fmt"
"log"
"os"
"cloud.google.com/go/datastore"
"google.golang.org/api/option"
)
var db *datastore.Client
func init() {
fmt.Println("INIT IN DB PACKAGE CALLED")
db = CreateDataStoreClient()
}
//CreateDataStoreClient client object
func CreateDataStoreClient() *datastore.Client {
serviceAccountFilePath := os.Getenv("SERVICE_ACCOUNT_PATH")
gcpProjectID := os.Getenv("PROJECT_ID")
// Create a datastore client.
client, err := datastore.NewClient(context.Background(), gcpProjectID, option.WithServiceAccountFile(serviceAccountFilePath))
if err != nil {
log.Fatal("ERROR IN CONNECTING TO DATASTORE")
}
return client
}
//GetDB ...
func GetDB() *datastore.Client {
return db
}
我正在尝试在下面的控制器enter code here
func (ctrl CloudController) GenerateAPIKey(c *gin.Context) {
// get the data store client
dsClient := db.GetDB()
// Request
//ctx := appengine.NewContext(c.Request)
ctx := context.Background()
music := &Music{
apiKey: generateAPIKey(40),
}
key := datastore.IncompleteKey("Account", nil)
if _, err := dsClient.Put(ctx, key, music); err != nil {
fmt.Println(err)
c.JSON(200, gin.H{"message": "error in generating api key"})
}
c.JSON(200, gin.H{"apiKey": music.apiKey})
}