小编典典

使用Go连接到Google Cloud DataStore

go

我正在尝试从Go连接到云数据存储。我使用了此处提供的示例代码-https:
//github.com/GoogleCloudPlatform/gcloud-
golang。

这些是我的代码的相关位:

func getCtx() context.Context {
    // Initialize an authorized transport with Google Developers Console
    // JSON key. Read the google package examples to learn more about
    // different authorization flows you can use.
    // http://godoc.org/golang.org/x/oauth2/google
    opts, err := oauth2.New(
        google.ServiceAccountJSONKey("CassandraTest-key.json"),
        oauth2.Scope(datastore.ScopeDatastore),
    )
    if err != nil {
        log.Fatal(err)
    }

    //titanium-goods-766 is the project id for CassandraTest (under sthilakan@eyeota.com)

    ctx := cloud.NewContext("titanium-goods-766", &http.Client{Transport: opts.NewTransport()})

    // Use the context (see other examples)
    return ctx
}

type contactInfoEntity struct {
    EmailKey  *datastore.Key
    FirstName string
    LastName  string
}

func main() {
    ctx := getCtx()
    fmt.Println("successfully got context", ctx)

    err := putEntity(ctx, "fname1", "lname1", "email1")

    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("success")
    }
}

func putEntity(ctx context.Context, firstName string, lastName string, email string) error {
    key := datastore.NewKey(ctx, "contactInfoEntity", email, 0, nil)

    contactInfoEntity := contactInfoEntity{
        EmailKey:  key,
        FirstName: firstName,
        LastName:  lastName,
    }

    _, err := datastore.Put(ctx, key, &contactInfoEntity)

    return err
}

我始终收到此错误。

Error: error during call, http status code: 403 Unauthorized.

我已禁用并重新启用了数据存储区api几次如此处的建议:所有请求都返回403
Unauthorized。我也尝试过删除和添加服务帐户。

(我试图连接我的计算引擎实例数据存储在这里使用的步骤-
https://cloud.google.com/datastore/docs并能正常工作)。

有没有人从go连接到云数据存储?

此致Sathya


阅读 310

收藏
2020-07-02

共1个答案

小编典典

访问Cloud Datastore需要两个范围:datastore.ScopeDatastoredatastore.ScopeUserEmail

opts, err := oauth2.New(
    google.ServiceAccountJSONKey("CassandraTest-key.json"),
    oauth2.Scope(datastore.ScopeDatastore, datastore.ScopeUserEmail),
)
2020-07-02