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),
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计