// datastore1
package main
import (
"fmt"
"io/ioutil"
"log"
"time"
"golang.org/x/net/context"
"golang.org/x/oauth2/google"
"google.golang.org/cloud"
"google.golang.org/cloud/datastore"
)
const (
// ScopeDatastore grants permissions to view and/or manage datastore entities
copeDatastore = "https://www.googleapis.com/auth/datastore"
// ScopeUserEmail grants permission to view the user's email address.
// It is required to access the datastore.
ScopeUserEmail = "https://www.googleapis.com/auth/userinfo.email"
)
type ehrEntity struct {
email *datastore.Key
firstname string
lastname string
address string
age int8
dateofbirth time.Time
sex bool
}
func getCtx() *datastore.Client {
// 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
jsonKey, err := ioutil.ReadFile("filename.json")
opts, err := google.JWTConfigFromJSON(
jsonKey,
datastore.ScopeDatastore,
datastore.ScopeUserEmail,
)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
client, err := datastore.NewClient(ctx, "xxxx", cloud.WithTokenSource(opts.TokenSource(ctx)))
if err != nil {
log.Fatal(err)
}
// Use the context (see other examples)
return client
}
func ExampleGet() {
ctx := context.Background()
client, err := datastore.NewClient(ctx, "xxxx")
if err != nil {
log.Fatal(err)
}
key := datastore.NewKey(ctx, "User", "tluu@abc.com", 0, nil)
ehr := ehrEntity{
nil,
"tri",
"luu",
"addr1",
20,
time.Date(2009, time.January, 10, 23, 0, 0, 0, time.UTC),
false}
if err := client.Get(ctx, key, ehr); err != nil {
log.Fatal(err)
}
}
func main() {
getCtx()
fmt.Println("Pass authentication")
ExampleGet()
}
当我运行go文件时,它返回错误如下:
通过身份验证(传递getCtx()函数)。
ExampleGet()中的错误 可能在
ctx := context.Background()
client, err := datastore.NewClient(ctx, "xxxx")
if err != nil {
log.Fatal(err)
}
错误: 2016/01/09 22:08:43发表https://www.googleapis.com/datastore/v1beta2/datasets/xxxx/lookup:oauth2:无法获取令牌:400 Bad Request 回复:{ “错误”:“invalid_grant” }
如何解决此错误?
答案 0 :(得分:0)
这似乎对我有用。
如果您使用的是Linux,请尝试以下操作:
1. apt-get update
2. apt-get install ntp
3. /etc/init.d/ntp restart