golang自动生成Google API接口的插件库google的使用
Golang 自动生成 Google API 接口的插件库 google 的使用
Google APIs Go 客户端库
这是从 Google Discovery Service 的 JSON 描述文件自动生成的 Go 库集合。
快速开始
首先安装所需的 API 客户端库:
$ go get google.golang.org/api/tasks/v1
$ go get google.golang.org/api/moderator/v1
$ go get google.golang.org/api/urlshortener/v1
... etc ...
然后可以在代码中使用:
package main
import (
"context"
"net/http"
"google.golang.org/api/urlshortener/v1"
)
func main() {
ctx := context.Background()
svc, err := urlshortener.NewService(ctx)
// ...
}
授权认证
默认情况下,每个 API 将使用[Google 应用程序默认凭据]进行授权。这允许您的应用程序在许多环境中运行而无需显式配置。
// import "google.golang.org/api/sheets/v4"
client, err := sheets.NewService(ctx)
要使用 JSON 密钥文件授权,请将 option.WithCredentialsFile
传递给所需包的 NewService
函数:
client, err := sheets.NewService(ctx, option.WithCredentialsFile("path/to/keyfile.json"))
您可以使用 golang.org/x/oauth2
包创建 oauth2.TokenSource
来更好地控制授权。然后将 option.WithTokenSource
传递给 NewService
函数:
tokenSource := ...
svc, err := sheets.NewService(ctx, option.WithTokenSource(tokenSource))
状态
这些是自动生成的 Go 库,因此它们可能包含从一个版本到下一个版本的破坏性更改。生成器本身及其生成的代码因此被视为测试版。
这些客户端库由 Google 官方支持。但是,这些库被认为是完整的并且处于维护模式。这意味着我们将解决关键错误和安全问题,但不会添加任何新功能。
完整示例
下面是一个使用 Google Sheets API 的完整示例:
package main
import (
"context"
"fmt"
"log"
"google.golang.org/api/option"
"google.golang.org/api/sheets/v4"
)
func main() {
ctx := context.Background()
// 使用服务账号密钥文件认证
client, err := sheets.NewService(ctx, option.WithCredentialsFile("credentials.json"))
if err != nil {
log.Fatalf("Unable to retrieve Sheets client: %v", err)
}
// 电子表格ID和范围
spreadsheetId := "your-spreadsheet-id"
readRange := "Sheet1!A1:C3"
// 读取数据
resp, err := client.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v", err)
}
// 打印数据
if len(resp.Values) == 0 {
fmt.Println("No data found.")
} else {
fmt.Println("Name, Major:")
for _, row := range resp.Values {
fmt.Printf("%s, %s\n", row[0], row[1])
}
}
}
注意事项
- 这些库是自动生成的,可能会包含破坏性更改
- 处于维护模式,只修复关键错误和安全问题
- 对于 Google Cloud Platform API,建议使用 Cloud Client Libraries for Go
更多关于golang自动生成Google API接口的插件库google的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
1 回复