The google api go client library has been around for a quite some time. It can be used to access a all of the google discovery services apis. Google drive, google sheets, YouTube api are just a few of the Discovery services apis. I thought today we would have a look at uploading a file to google drive using the google drive api and the google api go client library.
For this sample I will be using a service account. You will need to create service account credentials over on google cloud console for this to work.
Authorize the app
In order to make requests to the api our app first needs to be authorized. Doing this with Go is quite easy thanks to the Google api go client library. It handles all of the hard parts for us.
I have created a few constants to begin with. This will enable me to make my code easy to change in the future. The first constant is the path to the service account key file I downloaded from Google cloud console, followed by the path to the file I will be uploading, and finally the scope of authorization needed to use the create method.
The file.create method requires write access, so here i will be using the fill drive scope.
const (
ServiceAccount = "C:\\Youtube\\dev\\ServiceAccountCred.json" // Please set the json file of Service account.
filename = "C:\\Development\\FreeLance\\GoogleSamples\\Data\\dummy.txt" // Filename
SCOPE = drive.DriveScope
)
Now we we will create our drive service. The drive service object has the service account credentials constant, and the scopes constant passed to it.
ctx := context.Background() srv, err := drive.NewService(ctx, option.WithCredentialsFile(ServiceAccount), option.WithScopes(SCOPE)) if err != nil { log.Fatalf("Warning: Unable to create drive Client %v", err) }
Uploading the file
Files are created in two parts, the first thing we need to do is set the file meta data. The file meta data describes the file itself. Name, mimetype, description, and even what folder you would like to upload the file to can be set in the file meta data.
Once the metadata has been set you can upload the file itself.
file, err := os.Open(filename)
info, _ := file.Stat()
if err != nil {
log.Fatalf("Warning: %v", err)
}
if err != nil {
log.Fatalln(err)
}
defer file.Close()
// Create File metadata
f := &drive.File{Name: info.Name()}
// Create and upload the file
res, err := srv.Files.
Create(f).
Media(file). //context.Background(), file, fileInf.Size(), baseMimeType).
ProgressUpdater(func(now, size int64) { fmt.Printf("%d, %d\r", now, size) }).
Do()
Full Sample
Following is the full sample code for this. It uploads the file directly to the service accounts drive account. You could share a folder with the service account, and then set parents in the file metadata to upload the file to a directory on your personal drive account.
package main
import (
"context"
"fmt"
"google.golang.org/api/option"
"log"
"os"
drive "google.golang.org/api/drive/v3"
)
// Constants
const (
ServiceAccount = "C:\\Youtube\\dev\\ServiceAccountCred.json" // Please set the json file of Service account.
filename = "C:\\Development\\FreeLance\\GoogleSamples\\Data\\dummy.txt" // Filename
SCOPE = drive.DriveScope
)
func main() {
ctx := context.Background()
srv, err := drive.NewService(ctx, option.WithCredentialsFile(ServiceAccount), option.WithScopes(SCOPE))
if err != nil {
log.Fatalf("Warning: Unable to create drive Client %v", err)
}
file, err := os.Open(filename)
info, _ := file.Stat()
if err != nil {
log.Fatalf("Warning: %v", err)
}
if err != nil {
log.Fatalln(err)
}
defer file.Close()
// Create File metadata
f := &drive.File{Name: info.Name()}
// Create and upload the file
res, err := srv.Files.
Create(f).
Media(file). //context.Background(), file, fileInf.Size(), baseMimeType).
ProgressUpdater(func(now, size int64) { fmt.Printf("%d, %d\r", now, size) }).
Do()
if err != nil {
log.Fatalln(err)
}
fmt.Printf("New file id: %s\n", res.Id)
}
Conclusion
Go can be a very nice language to do back end processes with. Uploading a file to google drive with go is quite easy thanks to the google api go client library.