Go 快速入門導覽課程

快速入門導覽課程說明如何設定及執行呼叫 Google Workspace API 的應用程式。

Google Workspace 快速入門導覽課程會使用 API 用戶端程式庫,處理驗證和授權流程的部分細節。建議您為自己的應用程式採用用戶端程式庫。本快速入門導覽課程採用適用於測試環境的簡易驗證方法。如果是實際工作環境,建議您先瞭解驗證與授權,再選擇適合應用程式的存取憑證

建立 Go 指令列應用程式,向 Google Drive API 提出要求。

目標

  • 設定環境。
  • 設定範例。
  • 執行範例。

先備知識

  • 擁有已啟用 Google 雲端硬碟的 Google 帳戶。

設定環境

如要完成本快速入門導覽課程,請設定環境。

啟用 API

使用 Google API 前,您必須先在 Google Cloud 專案中啟用 API。您可以在單一 Google Cloud 專案中啟用一或多個 API。
  • 在 Google Cloud 控制台中,啟用 Google Drive API。

    啟用 API

如果您使用新的 Google Cloud 專案完成本快速入門導覽課程,請設定 OAuth 同意畫面,並將自己新增為測試使用者。如果您已經為 Cloud 專案完成這個步驟,請跳到下一部分。

  1. 在 Google Cloud 控制台中,依序前往「選單」圖示 >「API 和服務」>「OAuth 同意畫面」

    前往 OAuth 同意畫面

  2. 在「使用者類型」部分選取「內部」,然後按一下「建立」
  3. 填寫應用程式註冊表單,然後按一下「儲存並繼續」
  4. 您現在可以略過新增範圍的步驟,然後按一下「儲存並繼續」。 日後建立要在 Google Workspace 機構外部使用的應用程式時,您必須將「使用者類型」變更為「外部」,再新增應用程式所需的授權範圍。

  5. 查看應用程式註冊摘要。如要修改資訊,請按一下「編輯」。如果應用程式註冊正確無誤,請按一下「Back to Dashboard」(返回資訊主頁)

授權電腦版應用程式憑證

如要驗證使用者及存取應用程式中的使用者資料,您必須建立一或多個 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 Drive API Go 用戶端程式庫和 OAuth2.0 套件:

    go get google.golang.org/api/drive/v3
    go get golang.org/x/oauth2/google
    

設定範例

  1. 在工作目錄中,建立名為 quickstart.go 的檔案。

  2. 在檔案中貼上下列程式碼:

    drive/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/drive/v3"
    	"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 client secret file: %v", err)
    	}
    
    	// If modifying these scopes, delete your previously saved token.json.
    	config, err := google.ConfigFromJSON(b, drive.DriveMetadataReadonlyScope)
    	if err != nil {
    		log.Fatalf("Unable to parse client secret file to config: %v", err)
    	}
    	client := getClient(config)
    
    	srv, err := drive.NewService(ctx, option.WithHTTPClient(client))
    	if err != nil {
    		log.Fatalf("Unable to retrieve Drive client: %v", err)
    	}
    
    	r, err := srv.Files.List().PageSize(10).
    		Fields("nextPageToken, files(id, name)").Do()
    	if err != nil {
    		log.Fatalf("Unable to retrieve files: %v", err)
    	}
    	fmt.Println("Files:")
    	if len(r.Files) == 0 {
    		fmt.Println("No files found.")
    	} else {
    		for _, i := range r.Files {
    			fmt.Printf("%s (%s)\n", i.Name, i.Id)
    		}
    	}
    }
    

執行範例

  1. 在工作目錄中建構並執行範例:

    go run quickstart.go
    
  1. 第一次執行範例時,系統會提示您授予存取權:
    1. 如果尚未登入 Google 帳戶,請在系統提示時登入。如果您登入了多個帳戶,請選取一個要用於授權的帳戶。
    2. 然後點選 [Accept]

    Go 應用程式會執行並呼叫 Google Drive API。

    授權資訊會儲存在檔案系統中,因此下次執行程式碼範例時,系統不會提示授權。

後續步驟