package main
import (
"context"
"fmt"
"io"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
"google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
func main() {
// Set your Google Drive folder ID
folderID := "YOUR_FOLDER_ID"
// Set the path to the file you want to upload
filePath := "path/to/your/file.txt"
// Authenticate using a service account file (JSON key file)
creds, err := google.CredentialsFromJSON(context.Background(), []byte("YOUR_JSON_KEY"), drive.DriveFileScope)
if err != nil {
log.Fatalf("Failed to create credentials: %v", err)
}
// Create a Drive service client
driveService, err := drive.NewService(context.Background(), option.WithCredentials(creds))
if err != nil {
log.Fatalf("Failed to create Drive service: %v", err)
}
// Get the MIME type of the file
mimeType := getMimeType(filePath)
// Create metadata for the file
fileMetadata := &drive.File{
Name: filepath.Base(filePath),
MimeType: mimeType,
Parents: []string{folderID},
}
// Open the file for reading
file, err := os.Open(filePath)
if err != nil {
log.Fatalf("Failed to open file: %v", err)
}
defer file.Close()
// Create a file in Google Drive
createdFile, err := driveService.Files.Create(fileMetadata).Media(file).Do()
if err != nil {
log.Fatalf("Failed to create file: %v", err)
}
fmt.Printf("File '%s' uploaded successfully to Google Drive with ID: %s\n", createdFile.Name, createdFile.Id)
}
// getMimeType returns the MIME type of a file based on its extension.
func getMimeType(filePath string) string {
ext := strings.ToLower(filepath.Ext(filePath))
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
// Use a generic binary MIME type if the type cannot be determined
mimeType = "application/octet-stream"
}
return mimeType
}