2016-01-09 69 views
1
// 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", "[email protected]", 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() 
} 

當我去運行文件,它返回錯誤如下:錯誤400的oauth2谷歌雲存儲 - 去郎

通過認證(合格getCtx()函數)。

錯誤ExampleGet() 可在

ctx := context.Background() 
client, err := datastore.NewClient(ctx, "xxxx") 
if err != nil { 
    log.Fatal(err) 
    } 

錯誤: 2016年1月9日22時08分43秒發表https://www.googleapis.com/datastore/v1beta2/datasets/xxxx/lookup:的oauth2:無法獲取令牌:400錯誤的請求 響應:{ 「error」:「invalid_grant」 }

如何解決此錯誤?

+0

我有相同 - 任何進展?我試圖設置NTP來同步服務器時間。 –

回答

0

這似乎適用於我。

如果你是在Linux上嘗試以下方法:
1. apt-get的更新
2.易於得到安裝NTP
3. /etc/init.d/ntp重啓

+0

我試圖安裝ntp,啓動ntp服務,但它仍然錯誤:2016/01/18 21:17:11發佈https://www.googleapis.com/datastore/v1beta2/datasets/xxx/lookup:oauth2:can not取回令牌:400錯誤請求 迴應:{ 「錯誤」:「invalid_grant」 } –

+0

該死的,我希望這是解決方案。我這樣做後,我的服務器仍在工作。這意味着錯誤可能會回來。如果我找到某些東西,我會通知你。 –

+0

我在錯誤中看到的網址與您的網址不同。看看:http://stackoverflow.com/questions/34832424/suddenly-400-bad-request –