Skip to content

Instantly share code, notes, and snippets.

@oshiro-kazuma
Last active February 3, 2020 05:59
Show Gist options
  • Save oshiro-kazuma/720b395aa75ad0459bb450e42046bffe to your computer and use it in GitHub Desktop.
Save oshiro-kazuma/720b395aa75ad0459bb450e42046bffe to your computer and use it in GitHub Desktop.
サービスアカウントでGoogle Drive APIを呼び出す

サービスアカウントでGoogle Drive APIを呼び出す

1. Google Drive APIを有効にする

Image from Gyazo

2. サービスアカウントを作成する

参考

Image from Gyazo

3. キーを作成する

キーのタイプにはJSONを選択します。

Image from Gyazo

4. 対象のファイルのfile_idを取得する

Image from Gyazo

https://drive.google.com/open?id=1_ATVYJ06wyZkXooksMPt7oO3tvhEChUY

末尾の 1_ATVYJ06wyZkXooksMPt7oO3tvhEChUY がfile idです。

5. プログラムを実行

引数にfile_idを与える

go run main.go --file_id 1_ATVYJ06wyZkXooksMPt7oO3tvhEChUY

標準出力に、ファイルの内容が出力され、Google Driveからデータを取得できていることがわかります。

package main
import (
"context"
"flag"
"io/ioutil"
"log"
"google.golang.org/api/drive/v2"
"google.golang.org/api/option"
)
var fileID = flag.String("file_id", "", "google drive file id")
// 引数でfile_idを取得する
func init() {
flag.Parse()
if *fileID == "" {
flag.Usage()
log.Fatal("file_idを指定してください")
}
}
func main() {
// google drive api serviceを初期化
service, err := drive.NewService(context.Background(), option.WithCredentialsFile("credentials.json"))
if err != nil {
log.Fatal(err)
}
// テキストファイルを取得して表示する
text, err := download(service, *fileID)
if err != nil {
log.Fatalf("Unable to retrieve folder: %v", err)
}
print("テキストの内容 :" + string(text))
}
// ファイルをダウンロード
func download(service *drive.Service, fileID string) ([]byte, error) {
resp, err := service.Files.Get(fileID).Download()
if err != nil {
panic(err)
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment