您的用户是通过 Google Meet 使用 Google 课堂吗?请查看 Apps 脚本快速入门 - 了解如何在 Google Meet 课程中查看学生出席情况

Go 快速入门

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

快速入门介绍了如何设置和运行调用 Google Workspace API 的应用。

Google Workspace 快速入门使用 API 客户端库来处理身份验证和授权流程的一些详细信息。我们建议您为自己的应用使用客户端库。每个快速入门都要求您开启身份验证和授权,然后才能运行示例应用。如果您不熟悉 Google Workspace API 的身份验证和授权,请参阅身份验证和授权概览

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

目标

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

前提条件

  • 启用了 Google 课堂的 Google for Education 帐号。

设置您的环境

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

启用 API

在使用 Google API 之前,您需要先在 Google Cloud 项目中启用它们。您可以在单个 Google Cloud 项目中启用一个或多个 API。
  • 在 Google Cloud 控制台中,启用 Google 课堂 API。

    启用 API

为桌面应用授权凭据

如需以最终用户的身份进行身份验证并访问应用中的用户数据,您需要创建一个或多个 OAuth 2.0 客户端 ID。客户端 ID 用于向 Google 的 OAuth 服务器标识单个应用。如果您的应用在多个平台上运行,您必须为每个平台创建单独的客户端 ID。
  1. 在 Google Cloud 控制台中,转到“菜单”图标 > API 和服务 > 凭据

    进入“凭据”页面

  2. 点击创建凭据 > OAuth 客户端 ID
  3. 依次点击应用类型 > 桌面应用
  4. 名称字段中,输入凭据名称。此名称仅显示在 Google Cloud 控制台中。
  5. 点击创建。系统会显示 OAuth 客户端创建的屏幕,其中会显示您的新客户端 ID 和客户端密钥。
  6. 点击 OK。新创建的凭据会显示在 OAuth 2.0 客户端 ID 下。
  7. 将下载的 JSON 文件另存为 credentials.json,并将该文件移至工作目录。

准备工作区

  1. 创建工作目录:

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

    cd quickstart
    
  3. 初始化新模块:

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

    go get google.golang.org/api/classroom/v1
    go get golang.org/x/oauth2/google
    

设置示例

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

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

    classroom/quickstart/quickstart.go
    package main
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    
    	"golang.org/x/oauth2"
    	"golang.org/x/oauth2/google"
    	"google.golang.org/api/classroom/v1"
    	"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)
    }
    
    func main() {
    	ctx := context.Background()
    	b, err := os.ReadFile("credentials.json")
    	if err != nil {
    		log.Fatalf("Unable to read credentials file: %v", err)
    	}
    
    	// If modifying these scopes, delete your previously saved token.json.
    	config, err := google.ConfigFromJSON(b, classroom.ClassroomCoursesReadonlyScope)
    	if err != nil {
    		log.Fatalf("Unable to parse client secret file to config: %v", err)
    	}
    	client := getClient(config)
    
    	srv, err := classroom.NewService(ctx, option.WithHTTPClient(client))
    	if err != nil {
    		log.Fatalf("Unable to create classroom Client %v", err)
    	}
    
    	r, err := srv.Courses.List().PageSize(10).Do()
    	if err != nil {
    		log.Fatalf("Unable to retrieve courses. %v", err)
    	}
    	if len(r.Courses) > 0 {
    		fmt.Print("Courses:\n")
    		for _, c := range r.Courses {
    			fmt.Printf("%s (%s)\n", c.Name, c.Id)
    		}
    	} else {
    		fmt.Print("No courses found.")
    	}
    }
    

运行示例

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

    go run quickstart.go
    
  2. 在浏览器中,转到 http://localhost:8000

  3. 首次运行示例时,系统会提示您授予访问权限:

    1. 如果您尚未登录 Google 帐号,系统会提示您登录。如果您登录了多个帐号,请选择一个帐号用于授权。
    2. 点击接受
    3. 从浏览器中复制代码,并将其粘贴到命令行提示符中,然后按 Enter

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

您已成功创建了第一个向 Google Classroom API 发出请求的 Go 应用。

后续步骤