70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
"github.com/aws/aws-sdk-go/aws/credentials"
|
|
"github.com/aws/aws-sdk-go/aws/session"
|
|
"github.com/aws/aws-sdk-go/service/s3"
|
|
)
|
|
|
|
func main() {
|
|
|
|
if len(os.Args) != 7 {
|
|
fmt.Println("Usage: go run main.go <aws-region> <aws-access-key-id> <aws-secret-access-key> <bucket-name> </folder/file_name.ext OnS3> <file-path>")
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Extract bucket name and file path from command-line arguments
|
|
awsRegion := os.Args[1]
|
|
awsAccessKeyID := os.Args[2]
|
|
awsSecretAccessKey := os.Args[3]
|
|
bucketName := os.Args[4]
|
|
folderOnS3 := os.Args[5]
|
|
filePath := os.Args[6]
|
|
|
|
// Create an AWS session using provided credentials
|
|
sess, err := session.NewSession(&aws.Config{
|
|
Region: aws.String(awsRegion),
|
|
Credentials: credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, ""),
|
|
})
|
|
if err != nil {
|
|
fmt.Println("Error creating session:", err)
|
|
return
|
|
}
|
|
|
|
// Create an S3 service client
|
|
s3Client := s3.New(sess)
|
|
|
|
// Open the file for reading
|
|
file, err := os.Open(filePath)
|
|
if err != nil {
|
|
fmt.Println("Error opening file:", err)
|
|
return
|
|
}
|
|
defer file.Close()
|
|
|
|
// Get the file size
|
|
fileInfo, _ := file.Stat()
|
|
size := fileInfo.Size()
|
|
|
|
// Create an S3 upload parameters object
|
|
params := &s3.PutObjectInput{
|
|
Bucket: aws.String(bucketName),
|
|
Key: aws.String(folderOnS3),
|
|
// ACL: aws.String("bucket-owner-full-control"),
|
|
Body: file,
|
|
ContentLength: aws.Int64(size),
|
|
}
|
|
|
|
// Perform the upload
|
|
_, err = s3Client.PutObject(params)
|
|
if err != nil {
|
|
fmt.Println("Error uploading file:", err)
|
|
return
|
|
}
|
|
|
|
fmt.Println("File uploaded successfully!")
|
|
}
|