Google Cloud Storage (GCS) + GoLang - File Upload, Download, List, and Delete Example
To set up and use Google Cloud Storage in GoLang for uploading, listing, downloading, and deleting files, follow these steps:
1. Set Up Google Cloud Project
Create a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project or use an existing one.
Enable Google Cloud Storage API:
- Navigate to APIs & Services > Library in the console.
- Search for "Cloud Storage" and enable it for your project.
Create a Storage Bucket:
- Navigate to Storage > Browser in the console.
- Click Create Bucket, give it a unique name, choose a location, and configure other settings.
Set Up a Service Account:
- Go to IAM & Admin > Service Accounts.
- Create a new service account with the Storage Admin role.
- Generate a key (JSON) and download it to your local machine.
2. Install the GoLang Google Cloud Storage Library
Install the official library using go get
:
3. Configure Authentication
Set the GOOGLE_APPLICATION_CREDENTIALS
environment variable to point to the service account key:
4. Write the Complete Code
Below is a complete GoLang program for uploading, listing, downloading, and deleting files in Google Cloud Storage.
5. Run the Program
Save the code to a file (e.g., main.go
), and execute it:
6. Key Notes
- Replace placeholders:
your-project-id
with your GCP project ID.your-bucket-name
with the name of your Cloud Storage bucket.
- Ensure you have the correct permissions for your service account:
- Storage Admin for full control or Storage Object Admin for specific file operations.
- Validate the file paths (
example.txt
,downloaded_example.txt
) exist in the correct directory.
This setup will give you a functional GoLang program to handle file operations in Google Cloud Storage.