Home > Blockchain >  Golang - get list of files from a shared Google Drive folder
Golang - get list of files from a shared Google Drive folder

Time:03-10

I am trying to list files and their IDs from a Google Drive folder using a known folder ID.

The drive service set up seems to be successful. But, I get a panic attempting to populate a variable with the info. Here is a snippet of the code:

    driveService, err := drive.NewService(ctx, option.WithCredentialsFile("../serverFiles/credentials.json"))
    if err != nil {
        log.Printf("Unable to retrieve Drive client: %v", err)
    }

    r, err := driveService.Files.List().
        DriveId('XXXXXXXXXX').
        PageSize(10).
        Fields("nextPageToken, files(id, name)").
        Do()
    if err != nil {
        log.Fatalf("Unable to retrieve files: %v", err)
    }

Here is the error I get:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x14312db]

Thanks for any help.

EDIT
Thanks to @Tanaike's answer, I learned that I was confused about some points. I am not attempting to get a list of files from a shared Drive, but a shared folder.
I am using a service account to access. In another script the same service account is able to write to this same drive folder. So, I think permissions are OK.
Here is how I am now trying to get the list (driveService is set up the same as above)

    r, err := driveService.Files.List().
        Corpora("user").
        PageSize(10).
        Q("'XXXXXXXX' in parents").
        Fields("nextPageToken, files(id, name)").
        Do()

I still get the panic and signal.

CodePudding user response:

I believe your goal is as follows.

  • You want to retrieve the file list from the shared drive using googleapis for go.

In this case, how about the following modification?

From:

r, err := driveService.Files.List().
    DriveId('XXXXXXXXXX').
    PageSize(10).
    Fields("nextPageToken, files(id, name)").
    Do()

To:

r, err := driveService.Files.List().
    DriveId("XXXXXXXXXX").
    Corpora("drive").
    SupportsAllDrives(true).
    IncludeItemsFromAllDrives(true).
    PageSize(10).
    Fields("nextPageToken, files(id, name)").
    Do()

Note:

  • In this modification, it supposes that you have permission for reading the shared drive and you have already been able to use Drive API. Please be careful about this.

Reference:

  • Related