Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active September 21, 2023 17:01
Show Gist options
  • Select an option

  • Save tanaikech/7ee103c80759a8297da198a5d1e92fc8 to your computer and use it in GitHub Desktop.

Select an option

Save tanaikech/7ee103c80759a8297da198a5d1e92fc8 to your computer and use it in GitHub Desktop.

Revisions

  1. tanaikech revised this gist Sep 22, 2017. 1 changed file with 1 addition and 0 deletions.
    1 change: 1 addition & 0 deletions submit.md
    Original file line number Diff line number Diff line change
    @@ -140,3 +140,4 @@ Also I got the information for this sample from godoc and GitHub of google-api-g
    - Files.Create : [godoc](https://godoc.org/google.golang.org/api/drive/v3#FilesCreateCall) and [GitHub](https://github.com/google/google-api-go-client/blob/master/drive/v3/drive-gen.go#L3996)
    - Permissions.Create : [godoc](https://godoc.org/google.golang.org/api/drive/v3#Permission) and [GitHub](https://github.com/google/google-api-go-client/blob/master/drive/v3/drive-gen.go#L1388)

    I have answered this at [stackoverflow](https://stackoverflow.com/questions/46334646/google-drive-api-v3-create-and-upload-file/46337094#46337094).
  2. tanaikech revised this gist Sep 21, 2017. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions submit.md
    Original file line number Diff line number Diff line change
    @@ -1,8 +1,7 @@
    # Uploading CSV File as Spreadsheet and Modifying Permissions using Golang
    This sample script is for uploading CSV file as Spreadsheet and modifying permissions using Golang.

    I think that the detail information of google-api-go-client is a bit little. The sample scripts are so little. It retrieves most information from only [godoc](https://godoc.org/google.golang.org/api/drive/v3 and [GitHub](https://github.com/google/google-api-go-client/tree/master/drive). So I publish such sample scripts here. If this is useful for you, I'm glad.

    I think that the detail information of **google-api-go-client** is a bit little. The sample scripts are so little. It retrieves most information from only [godoc](https://godoc.org/google.golang.org/api/drive/v3) and [GitHub](https://github.com/google/google-api-go-client/tree/master/drive). So I publish such sample scripts here. If this is useful for you, I'm glad.

    ## Important points :
    1. Give mimeType of file that it wants to upload to ``options`` of ``Media(r io.Reader, options ...googleapi.MediaOption)``.
  3. tanaikech created this gist Sep 21, 2017.
    143 changes: 143 additions & 0 deletions submit.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,143 @@
    # Uploading CSV File as Spreadsheet and Modifying Permissions using Golang
    This sample script is for uploading CSV file as Spreadsheet and modifying permissions using Golang.

    I think that the detail information of google-api-go-client is a bit little. The sample scripts are so little. It retrieves most information from only [godoc](https://godoc.org/google.golang.org/api/drive/v3 and [GitHub](https://github.com/google/google-api-go-client/tree/master/drive). So I publish such sample scripts here. If this is useful for you, I'm glad.


    ## Important points :
    1. Give mimeType of file that it wants to upload to ``options`` of ``Media(r io.Reader, options ...googleapi.MediaOption)``.
    1. In order to give ``options``, use ``googleapi.ContentType()``.
    1. Give mimeType of file that it wants to convert, when it uploads it to Google Drive, to ``file`` of ``Create(file *File)``.
    1. In order to give ``file``, use ``&drive.File{}``.
    1. For installing permissions, use ``&drive.Permission{}``. Each parameter is the same to them for Python.

    **This sample script uses [Quickstart](https://developers.google.com/drive/v3/web/quickstart/go). So in order to use this sample script, at first, please do Step 1 and Step 2 of the Quickstart.**

    ## Sample script :
    ~~~go
    package main

    import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"

    "golang.org/x/net/context"
    "golang.org/x/oauth2"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/drive/v3"
    "google.golang.org/api/googleapi"
    )

    func getClient(ctx context.Context, config *oauth2.Config) *http.Client {
    cacheFile := "./go-quickstart.json"
    tok, err := tokenFromFile(cacheFile)
    if err != nil {
    tok = getTokenFromWeb(config)
    saveToken(cacheFile, tok)
    }
    return config.Client(ctx, tok)
    }

    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 code string
    if _, err := fmt.Scan(&code); err != nil {
    log.Fatalf("Unable to read authorization code %v", err)
    }
    tok, err := config.Exchange(oauth2.NoContext, code)
    if err != nil {
    log.Fatalf("Unable to retrieve token from web %v", err)
    }
    return tok
    }

    func tokenFromFile(file string) (*oauth2.Token, error) {
    f, err := os.Open(file)
    if err != nil {
    return nil, err
    }
    t := &oauth2.Token{}
    err = json.NewDecoder(f).Decode(t)
    defer f.Close()
    return t, err
    }

    func saveToken(file string, token *oauth2.Token) {
    fmt.Printf("Saving credential file to: %s\n", file)
    f, err := os.Create(file)
    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 := ioutil.ReadFile("client_secret.json")
    if err != nil {
    log.Fatalf("Unable to read client secret file: %v", err)
    }
    config, err := google.ConfigFromJSON(b, drive.DriveScope)
    if err != nil {
    log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
    client := getClient(ctx, config)
    srv, err := drive.New(client)
    if err != nil {
    log.Fatalf("Unable to retrieve drive Client %v", err)
    }


    // Upload CSV and convert to Spreadsheet
    filename := "sample.csv" // File you want to upload
    baseMimeType := "text/csv" // mimeType of file you want to upload
    convertedMimeType := "application/vnd.google-apps.spreadsheet" // mimeType of file you want to convert on Google Drive

    file, err := os.Open(filename)
    if err != nil {
    log.Fatalf("Error: %v", err)
    }
    defer file.Close()
    f := &drive.File{
    Name: filename,
    MimeType: convertedMimeType,
    }
    res, err := srv.Files.Create(f).Media(file, googleapi.ContentType(baseMimeType)).Do()
    if err != nil {
    log.Fatalf("Error: %v", err)
    }
    fmt.Printf("%s, %s, %s\n", res.Name, res.Id, res.MimeType)


    // Modify permissions
    permissiondata := &drive.Permission{
    Type: "domain",
    Role: "writer",
    Domain: "google.com",
    AllowFileDiscovery: true,
    }
    pres, err := srv.Permissions.Create(res.Id, permissiondata).Do()
    if err != nil {
    log.Fatalf("Error: %v", err)
    }
    fmt.Printf("%s, %s\n", pres.Type, pres.Role)
    }
    ~~~

    ## Result :
    sample.csv, ### file ID on Google Drive ###, application/vnd.google-apps.spreadsheet
    domain, writer

    ## References :
    Also I got the information for this sample from godoc and GitHub of google-api-go-client.

    - Files.Create : [godoc](https://godoc.org/google.golang.org/api/drive/v3#FilesCreateCall) and [GitHub](https://github.com/google/google-api-go-client/blob/master/drive/v3/drive-gen.go#L3996)
    - Permissions.Create : [godoc](https://godoc.org/google.golang.org/api/drive/v3#Permission) and [GitHub](https://github.com/google/google-api-go-client/blob/master/drive/v3/drive-gen.go#L1388)