实战指南:Go语言中的OAuth2认证
package main
import (
"context"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/people/v1"
"log"
)
func main() {
ctx := context.Background()
client, err := google.DefaultClient(ctx, people.UserinfoEmailScope)
if err != nil {
log.Fatalf("Failed to get Google Client: %v", err)
}
// 创建一个人员服务客户端
service, err := people.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Failed to create People service client: %v", err)
}
// 获取用户的人员信息
person, err := service.People.Get("people/me").PersonFields("names", "emailAddresses").Do()
if err != nil {
log.Fatalf("Failed to get current user's information: %v", err)
}
fmt.Printf("Logged in as %s\n", person.DisplayName)
}
这段代码首先设置了OAuth 2.0的认证流程,然后创建了一个与Google People API交互的客户端,并获取了当前登录用户的信息。这个过程展示了如何使用Go语言与Google的API进行交互,并且如何处理OAuth 2.0授权。
评论已关闭