# Golang

### 1. Install the Dependencies <a href="#id-1-install-the-dependencies" id="id-1-install-the-dependencies"></a>

To install the project dependencies, simply run the following command in your terminal:

```go
go mod init aws_s3
go get github.com/aws/aws-sdk-go-v2/service/s3
```

The following commands show how to retrieve the standard set of SDK modules to use in your application.

```go
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
```

### 2. Setup the Environment <a href="#id-2-setup-the-environment" id="id-2-setup-the-environment"></a>

We will be setting up two environment variables, `ACCESS_KEY` and `SECRET_KEY`, which are required to access the S3 Cloud Storage service. Assign the values of these variables to the values of your credential that you received.

```go
export ACCESS_KEY=<your-access-key>
export SECRET_KEY=<your-secret-key>
```

### 3. Minimal code example <a href="#id-3-list-all-buckets" id="id-3-list-all-buckets"></a>

```go
package main
 
import (
	"context"
	"log"
	"os"
	"strings"
 
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)
 
func main() {
	resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
		return aws.Endpoint{
			URL:           "S3_ENDPOINT_URL",
			SigningRegion: "us-east-1",
		}, nil
	})
 
	credentials := aws.CredentialsProviderFunc(func(ctx context.Context) (aws.Credentials, error) {
		return aws.Credentials{
			AccessKeyID:     "YOUR_ACCESS_KEY_ID",
			SecretAccessKey: "YOUR_SECRET_ACCESS_KEY",
		}, nil
	})
 
	// Load config
	cfg, err := config.LoadDefaultConfig(context.TODO(),
		config.WithCredentialsProvider(credentials),
		config.WithEndpointResolverWithOptions(resolver),
	)
	if err != nil {
		log.Fatal(err)
	}
 
	// Create an Amazon S3 service client
	s3Client := s3.NewFromConfig(cfg,
		func(o *s3.Options) {
			o.UsePathStyle = true
		},
	)
 
	filePath := "YOUR_FILE_PATH"
	// Get file name from filePath
	path := strings.Split(filePath, "/")
	fileName := path[len(path)-1]
 
	file, openErr := os.Open(filePath)
	if openErr != nil {
		log.Fatal(openErr)
	}
	defer file.Close()
	_, putErr := s3Client.PutObject(context.TODO(), &s3.PutObjectInput{
		Bucket: aws.String("YOUR_BUCKET_NAME"),
		Key:    aws.String(fileName),
		Body:   file,
	})
 
	if putErr != nil {
		panic(putErr)
	}
 
	log.Println("Successfully uploaded object")
}
```
