Uploading files to Google Drive with Go involves using the Google Drive API and the official Go client libraries. This guide walks you through the setup and implementation process.
1. Set Up Google Cloud Project
- Go to the Google Cloud Console.
- Create a new project or select an existing one.
- Enable the Google Drive API.
- Go to APIs & Services > Credentials and create an OAuth 2.0 Client ID.
- Download the
credentials.json
file.
2. Install Dependencies
Use the following commands to install the necessary Go packages:
go get -u google.golang.org/api/drive/v3
go get -u golang.org/x/oauth2/google
3. Authorize and Authenticate
Use OAuth2 to authorize access to your Google Drive. Here's a helper function to retrieve a token:
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"os"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func getClient(config *oauth2.Config) *http.Client {
tokenFile := "token.json"
token, err := tokenFromFile(tokenFile)
if err != nil {
token = getTokenFromWeb(config)
saveToken(tokenFile, token)
}
return config.Client(context.Background(), token)
}
func tokenFromFile(file string) (*oauth2.Token, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
token := &oauth2.Token{}
err = json.NewDecoder(f).Decode(token)
return token, err
}
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
log.Printf("Go to the following link in your browser:\n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read auth code: %v", err)
}
token, err := config.Exchange(context.Background(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return token
}
func saveToken(path string, token *oauth2.Token) {
f, err := os.Create(path)
if err != nil {
log.Fatalf("Unable to create file: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
4. Upload a File
Now you can upload a file to Google Drive:
package main
import (
"context"
"log"
"os"
"google.golang.org/api/drive/v3"
"google.golang.org/api/option"
)
func main() {
b, err := os.ReadFile("credentials.json")
if err != nil {
log.Fatalf("Unable to read client secret file: %v", err)
}
config, err := google.ConfigFromJSON(b, drive.DriveFileScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
srv, err := drive.NewService(context.Background(), option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve Drive client: %v", err)
}
f, err := os.Open("example.txt")
if err != nil {
log.Fatalf("Unable to open file: %v", err)
}
defer f.Close()
fileMetadata := &drive.File{Name: "UploadedExample.txt"}
file, err := srv.Files.Create(fileMetadata).Media(f).Do()
if err != nil {
log.Fatalf("Unable to upload file: %v", err)
}
log.Printf("File ID: %s", file.Id)
}
5. Run Your Program
Execute your Go application with:
go run yourfile.go
On the first run, you will be prompted to visit a URL to authorize access. Once authorized, a token will be stored and reused.
Conclusion
Uploading files to Google Drive with Go is a straightforward process once your credentials and token flow are properly set up. You can extend this implementation to include features like folder uploads, MIME type detection, and advanced permission settings.