使用ServiceAccount调用Google Drive Go API无法获取文件列表
问题描述
我尝试通过ServiceAccount调用Google Drive API连接我的云端硬盘,但调用文件列表查询接口时返回空结果。创建DriveService时无报错,ServiceAccountCred是直接在Google Cloud的服务账号页面生成(添加密钥>下载)的。
代码示例
func main() { ctx := context.Background() srv, err := drive.NewService(ctx, option.WithCredentialsFile("ServiceAccountCred.json"), option.WithScopes(drive.DriveScope)) if err != nil { log.Fatalf("Warning: Unable to create 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) } for _, res := range r.Files { fmt.Println(res.Name) } }
问题原因及解决办法
- 服务账号拥有独立的Drive存储空间:你当前代码访问的是服务账号自己的云端硬盘,这个空间默认是空的,所以返回空列表,而非你个人的Drive。
- 共享资源给服务账号:
- 打开个人Google Drive,找到需要授权的文件/文件夹,右键选择「共享」。
- 填入服务账号的邮箱(可在
ServiceAccountCred.json的client_email字段找到),设置对应权限(查看/编辑)后完成共享。
- 访问整个个人Drive的特殊情况:如果你需要服务账号访问整个个人Drive,仅适用于Google Workspace域名用户,需要联系域管理员配置域范围授权,让服务账号模拟你的身份访问Drive。
- 验证修复效果:共享完成后重新运行代码,即可获取到共享的文件列表。
内容的提问来源于stack exchange,提问作者mikasa12343
相关产品推荐
相关产品推荐

