Go 版快速入门

创建一个向 Google Drive Activity API 发出请求的 Go 命令行应用。

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。本快速入门使用一种简化的身份验证方法,该方法适用于测试环境。对于生产环境,我们建议您先了解身份验证和授权,然后再选择适合您应用的访问凭据。

本快速入门使用 Google Workspace 推荐的 API 客户端库来处理身份验证和授权流程的一些细节。

目标

  • 设置环境。
  • 设置示例。
  • 运行示例。

前提条件

  • Google 账号。

设置环境

如需完成本快速入门,请设置您的环境。

启用 API

在使用 Google API 之前,您需要在 Google Cloud 项目中启用它们。 您可以在单个 Google Cloud 项目中启用一个或多个 API。
  • 在 Google Cloud 控制台中,启用 Google 云端硬盘 Activity API。

    启用 API

如果您要使用新的 Google Cloud 云项目完成本快速入门,请配置 OAuth 权限请求页面。如果您已为 Cloud 项目完成此步骤,请跳至下一部分。

  1. 在 Google API 控制台中,依次前往菜单 > Google Auth 平台 > 品牌推广。

    前往“品牌塑造”

  2. 如果您已配置 Google Auth 平台,则可以在品牌推广、受众群体和数据访问中配置以下 OAuth 同意屏幕设置。如果您看到一条消息,提示尚未配置 Google Auth 平台,请点击开始使用:
    1. 在应用信息下的应用名称中,输入应用的名称。
    2. 在用户支持邮箱中,选择一个支持电子邮件地址,以便用户在对自己的同意情况有疑问时与您联系。
    3. 点击下一步。
    4. 在受众群体下,选择内部。
    5. 点击下一步。
    6. 在联系信息下,输入一个电子邮件地址,以便您接收有关项目变更的通知。
    7. 点击下一步。
    8. 在完成部分,查看 Google API 服务用户数据政策,如果您同意该政策,请选择我同意 Google API 服务:用户数据政策。
    9. 点击继续。
    10. 点击创建。
  3. 目前,您可以跳过添加范围的步骤。 未来,如果您创建的应用供 Google Workspace 组织以外的用户使用,则必须将用户类型更改为外部。然后,添加应用所需的授权范围。如需了解详情,请参阅完整的配置 OAuth 同意指南。

为桌面应用授权凭据

如需对最终用户进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台分别创建客户端 ID。
  1. 在 Google Cloud 控制台中,依次前往菜单 > Google Auth 平台 > 客户端。

    前往“客户”页面

  2. 点击创建客户端。
  3. 依次点击应用类型 > 桌面应用。
  4. 在名称字段中,输入凭据的名称。此名称仅在 Google Cloud 控制台中显示。
  5. 点击创建。

    新创建的凭证会显示在“OAuth 2.0 客户端 ID”下。

  6. 将下载的 JSON 文件另存为 credentials.json,然后将该文件移动到您的工作目录。

准备工作区

  1. 创建工作目录:

    mkdir quickstart
    
  2. 切换到工作目录:

    cd quickstart
    
  3. 初始化新模块:

    go mod init quickstart
    
  4. 获取 Google Drive Activity API Go 客户端库和 OAuth2.0 软件包:

    go get google.golang.org/api/driveactivity/v2
    go get golang.org/x/oauth2/google
    

设置示例

  1. 在工作目录中,创建一个名为 quickstart.go 的文件。

  2. 在文件中,粘贴以下代码:

    drive/activity-v2/quickstart/quickstart.go
    package main
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    	"reflect"
    	"strings"
    
    	"golang.org/x/oauth2"
    	"golang.org/x/oauth2/google"
    	"google.golang.org/api/driveactivity/v2"
    	"google.golang.org/api/option"
    )
    
    // Retrieve a token, saves the token, then returns the generated client.
    func getClient(config *oauth2.Config) *http.Client {
    	// The file token.json stores the user's access and refresh tokens, and is
    	// created automatically when the authorization flow completes for the first
    	// time.
    	tokFile := "token.json"
    	tok, err := tokenFromFile(tokFile)
    	if err != nil {
    		tok = getTokenFromWeb(config)
    		saveToken(tokFile, tok)
    	}
    	return config.Client(context.Background(), tok)
    }
    
    // Request a token from the web, then returns the retrieved token.
    func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
    	authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
    	fmt.Printf("Go to the following link in your browser then type the "+
    		"authorization code: \n%v\n", authURL)
    
    	var authCode string
    	if _, err := fmt.Scan(&authCode); err != nil {
    		log.Fatalf("Unable to read authorization code: %v", err)
    	}
    
    	tok, err := config.Exchange(context.TODO(), authCode)
    	if err != nil {
    		log.Fatalf("Unable to retrieve token from web: %v", err)
    	}
    	return tok
    }
    
    // Retrieves a token from a local file.
    func tokenFromFile(file string) (*oauth2.Token, error) {
    	f, err := os.Open(file)
    	if err != nil {
    		return nil, err
    	}
    	defer f.Close()
    	tok := &oauth2.Token{}
    	err = json.NewDecoder(f).Decode(tok)
    	return tok, err
    }
    
    // Saves a token to a file path.
    func saveToken(path string, token *oauth2.Token) {
    	fmt.Printf("Saving credential file to: %s\n", path)
    	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
    	if err != nil {
    		log.Fatalf("Unable to cache oauth token: %v", err)
    	}
    	defer f.Close()
    	json.NewEncoder(f).Encode(token)
    }
    
    // Returns a string representation of the first elements in a list.
    func truncated(array []string) string {
    	return truncatedTo(array, 2)
    }
    
    // Returns a string representation of the first elements in a list.
    func truncatedTo(array []string, limit int) string {
    	var contents string
    	var more string
    	if len(array) <= limit {
    		contents = strings.Join(array, ", ")
    		more = ""
    	} else {
    		contents = strings.Join(array[0:limit], ", ")
    		more = ", ..."
    	}
    	return fmt.Sprintf("[%s%s]", contents, more)
    }
    
    // Returns the name of a set property in an object, or else "unknown".
    func getOneOf(m interface{}) string {
    	v := reflect.ValueOf(m)
    	for i := 0; i < v.NumField(); i++ {
    		if !v.Field(i).IsNil() {
    			return v.Type().Field(i).Name
    		}
    	}
    	return "unknown"
    }
    
    // Returns a time associated with an activity.
    func getTimeInfo(activity *driveactivity.DriveActivity) string {
    	if activity.Timestamp != "" {
    		return activity.Timestamp
    	}
    	if activity.TimeRange != nil {
    		return activity.TimeRange.EndTime
    	}
    	return "unknown"
    }
    
    // Returns the type of action.
    func getActionInfo(action *driveactivity.ActionDetail) string {
    	return getOneOf(*action)
    }
    
    // Returns user information, or the type of user if not a known user.
    func getUserInfo(user *driveactivity.User) string {
    	if user.KnownUser != nil {
    		if user.KnownUser.IsCurrentUser {
    			return "people/me"
    		}
    		return user.KnownUser.PersonName
    	}
    	return getOneOf(*user)
    }
    
    // Returns actor information, or the type of actor if not a user.
    func getActorInfo(actor *driveactivity.Actor) string {
    	if actor.User != nil {
    		return getUserInfo(actor.User)
    	}
    	return getOneOf(*actor)
    }
    
    // Returns information for a list of actors.
    func getActorsInfo(actors []*driveactivity.Actor) []string {
    	actorsInfo := make([]string, len(actors))
    	for i := range actors {
    		actorsInfo[i] = getActorInfo(actors[i])
    	}
    	return actorsInfo
    }
    
    // Returns the type of a target and an associated title.
    func getTargetInfo(target *driveactivity.Target) string {
    	if target.DriveItem != nil {
    		return fmt.Sprintf("driveItem:\"%s\"", target.DriveItem.Title)
    	}
    	if target.Drive != nil {
    		return fmt.Sprintf("drive:\"%s\"", target.Drive.Title)
    	}
    	if target.FileComment != nil {
    		parent := target.FileComment.Parent
    		if parent != nil {
    			return fmt.Sprintf("fileComment:\"%s\"", parent.Title)
    		}
    		return "fileComment:unknown"
    	}
    	return getOneOf(*target)
    }
    
    // Returns information for a list of targets.
    func getTargetsInfo(targets []*driveactivity.Target) []string {
    	targetsInfo := make([]string, len(targets))
    	for i := range targets {
    		targetsInfo[i] = getTargetInfo(targets[i])
    	}
    	return targetsInfo
    }
    
    func main() {
    	ctx := context.Background()
    	b, err := os.ReadFile("credentials.json")
    	if err != nil {
    		log.Fatalf("Unable to read client secret file: %v", err)
    	}
    
    	// If modifying these scopes, delete your previously saved token.json.
    	config, err := google.ConfigFromJSON(b, driveactivity.DriveActivityReadonlyScope)
    	if err != nil {
    		log.Fatalf("Unable to parse client secret file to config: %v", err)
    	}
    	client := getClient(config)
    
    	srv, err := driveactivity.NewService(ctx, option.WithHTTPClient(client))
    	if err != nil {
    		log.Fatalf("Unable to retrieve driveactivity Client %v", err)
    	}
    
    	q := driveactivity.QueryDriveActivityRequest{PageSize: 10}
    	r, err := srv.Activity.Query(&q).Do()
    	if err != nil {
    		log.Fatalf("Unable to retrieve list of activities. %v", err)
    	}
    
    	fmt.Println("Recent Activity:")
    	if len(r.Activities) > 0 {
    		for _, a := range r.Activities {
    			time := getTimeInfo(a)
    			action := getActionInfo(a.PrimaryActionDetail)
    			actors := getActorsInfo(a.Actors)
    			targets := getTargetsInfo(a.Targets)
    			fmt.Printf("%s: %s, %s, %s\n", time, truncated(actors), action, truncated(targets))
    		}
    	} else {
    		fmt.Print("No activity.")
    	}
    }

运行示例

  1. 在工作目录中,构建并运行示例:

    go run quickstart.go
    
  1. 首次运行该示例时,系统会提示您授权访问:
    1. 如果您尚未登录 Google 账号,请在系统提示时登录。如果您已登录多个账号,请选择一个账号用于授权。
    2. 点击接受。

    您的 Go 应用运行并调用 Google Drive Activity API。

    授权信息存储在文件系统中,因此下次运行示例代码时,系统不会提示您进行授权。

后续步骤