Go 빠른 시작

빠른 시작에서는 Google Workspace API

Google Workspace 빠른 시작에서는 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 세부 정보를 확인하세요. 따라서 자체 앱에 클라이언트 라이브러리를 사용합니다. 이 빠른 시작에서는 테스트에 적합한 간소화된 인증 접근 방식 환경입니다 프로덕션 환경의 경우 인증 및 승인 이전 액세스 사용자 인증 정보 선택 선택할 수 있습니다.

Google Cloud 콘솔로 Google Apps Script API.

목표

  • 환경을 설정합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google Drive가 사용 설정된 Google 계정

환경 설정

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Google Apps Script API를 사용 설정합니다.

    API 사용 설정

새 Google Cloud 프로젝트를 사용하여 이 빠른 시작을 완료하는 경우 본인을 테스트 사용자로 추가합니다. 이미 계정을 이 단계를 완료한 경우에는 다음 섹션으로 건너뛰세요.

  1. Google Cloud 콘솔에서 메뉴 로 이동합니다. > API 및 서비스 > OAuth 동의 화면.

    OAuth 동의 화면으로 이동

  2. 사용자 유형으로 내부를 선택한 다음 만들기를 클릭합니다.
  3. 앱 등록 양식을 작성한 다음 저장하고 계속하기를 클릭합니다.
  4. 지금은 범위 추가를 건너뛰고 저장 후 계속을 클릭할 수 있습니다. 나중에 외부에서 사용하기 위해 앱을 만들 때 Google Workspace 조직의 경우 사용자 유형외부로 변경한 다음 앱에 필요한 승인 범위를 추가합니다.

  5. 앱 등록 요약을 검토합니다. 변경하려면 수정을 클릭합니다. 앱이 등록이 확인되면 대시보드로 돌아가기를 클릭합니다.

데스크톱 애플리케이션의 사용자 인증 정보 승인

최종 사용자를 인증하고 앱의 사용자 데이터에 액세스하려면 다음을 실행해야 합니다. 하나 이상의 OAuth 2.0 클라이언트 ID를 만듭니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  4. 이름 필드에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 만들기를 클릭합니다. OAuth 클라이언트 생성 화면이 표시되고 새 클라이언트 ID와 클라이언트 비밀번호가 표시됩니다.
  6. 확인을 클릭합니다. 새로 생성된 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  7. 다운로드한 JSON 파일을 credentials.json로 저장하고 작업 디렉터리로 이동합니다

작업공간 준비

  1. 작업 디렉터리를 만듭니다.

    mkdir quickstart
    
  2. 작업 디렉터리로 변경합니다.

    cd quickstart
    
  3. 새 모듈을 초기화합니다.

    go mod init quickstart
    
  4. Google Apps Script API Go 클라이언트 라이브러리 및 OAuth2.0 패키지를 가져옵니다.

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

샘플 설정

  1. 작업 디렉터리에 quickstart.go라는 파일을 만듭니다.

  2. 파일에 다음 코드를 붙여넣습니다.

    apps_script/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/option"
    	"google.golang.org/api/script/v1"
    )
    
    // 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, "https://www.googleapis.com/auth/script.projects")
    	if err != nil {
    		log.Fatalf("Unable to parse client secret file to config: %v", err)
    	}
    	client := getClient(config)
    
    	srv, err := script.NewService(ctx, option.WithHTTPClient(client))
    	if err != nil {
    		log.Fatalf("Unable to retrieve Script client: %v", err)
    	}
    
    	req := script.CreateProjectRequest{Title: "My Script"}
    	createRes, err := srv.Projects.Create(&req).Do()
    	if err != nil {
    		// The API encountered a problem.
    		log.Fatalf("The API returned an error: %v", err)
    	}
    	content := &script.Content{
    		ScriptId: createRes.ScriptId,
    		Files: []*script.File{{
    			Name:   "hello",
    			Type:   "SERVER_JS",
    			Source: "function helloWorld() {\n  console.log('Hello, world!');}",
    		}, {
    			Name: "appsscript",
    			Type: "JSON",
    			Source: "{\"timeZone\":\"America/New_York\",\"exceptionLogging\":" +
    				"\"CLOUD\"}",
    		}},
    	}
    	updateContentRes, err := srv.Projects.UpdateContent(createRes.ScriptId,
    		content).Do()
    	if err != nil {
    		// The API encountered a problem.
    		log.Fatalf("The API returned an error: %v", err)
    	}
    	log.Printf("https://script.google.com/d/%v/edit", updateContentRes.ScriptId)
    }
    

샘플 실행

  1. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    go run quickstart.go
    
  1. 샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다. <ph type="x-smartling-placeholder">
      </ph>
    1. 아직 Google 계정에 로그인하지 않은 경우 메시지가 표시되면 로그인합니다. 만약 여러 계정에 로그인한 경우 승인에 사용할 계정 1개를 선택하세요.
    2. 수락을 클릭합니다.

    Go 애플리케이션이 실행되고 Google Apps Script API를 호출합니다.

    승인 정보는 파일 시스템에 저장되므로 다음에 샘플을 실행할 때 승인하라는 메시지가 표시되지 않습니다.

다음 단계