我正在尝试从在Google App Engine Go 1.11 Standard Environment上运行的应用程序通过 API 访问 google 电子表格。不幸的是,应用程序无法读取此电子表格。
我在Spreadsheets.Values.Get
通话中遇到下一个错误:
googleapi: Error 403: Request had insufficient authentication scopes., forbidden
示例代码
// Sample app showing issue with GAE -> google spreadsheets
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"cloud.google.com/go/compute/metadata"
"golang.org/x/oauth2/google"
"google.golang.org/api/sheets/v4"
)
func main() {
http.HandleFunc("/", indexHandler)
// [START setting_port]
port := os.Getenv("PORT")
if port == "" {
port = "8080"
log.Printf("Defaulting to port %s\n", port)
}
// let's check app engine instance scopes
scopes, _ := metadata.Get("instance/service-accounts/default/scopes")
log.Printf("[DEBUG] metadata scopes: %s.\n", scopes)
log.Printf("Listening on port %s", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
// [END setting_port]
}
// indexHandler responds to requests with our greeting.
func indexHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
client, _ := google.DefaultClient(ctx, "https://www.googleapis.com/auth/spreadsheets.readonly")
srv, err := sheets.New(client)
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"
readRange := "Class Data!A2:E"
resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v\n", err)
}
重现步骤:
1) 部署应用程序:gcloud app deploy
2) 在浏览器中打开(您将获得 502):gcloud app browse
3) 检查日志:gcloud app logs read
呼唤远方
相关分类