使用go连接到谷歌云数据存储区

时间:2014-12-15 08:17:03

标签: go google-cloud-datastore

我正在尝试从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几次(如此处所示:All Requests return 403 Unauthorized)。我也尝试删除并添加服务帐户。

(我尝试使用此处的步骤 - https://cloud.google.com/datastore/docs将我的计算引擎实例连接到数据存储区,并且工作正常。)

是否有人连接到云数据存储区?

此致 沙迪亚

1 个答案:

答案 0 :(得分:3)

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

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