douba1617 2014-12-15 08:17
浏览 105
已采纳

使用Go连接到Google Cloud DataStore

I am trying to connect to cloud datastore from Go. I used the sample code given here - https://github.com/GoogleCloudPlatform/gcloud-golang.

These are the relevant bits of my code:

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
}

I get this error consistently.

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

I have disabled and reenabled datastore api a few times (as suggested here: All Requests return 403 Unauthorized). I have also tried removing and adding the service account.

(I tried to connect my compute engine instance to datastore using the steps here - https://cloud.google.com/datastore/docs and it works fine).

Have anyone connected to cloud datastore from go ?

Regards, Sathya

  • 写回答

1条回答 默认 最新

  • dpd2349 2014-12-16 17:38
    关注

    Accessing Cloud Datastore requires two scopes: datastore.ScopeDatastore and datastore.ScopeUserEmail:

    opts, err := oauth2.New(
        google.ServiceAccountJSONKey("CassandraTest-key.json"),
        oauth2.Scope(datastore.ScopeDatastore, datastore.ScopeUserEmail),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况