Using variable values

Asked

Viewed 45 times

0

I have this code in GO and as you can see I use two constants to pass the region and the name of Bucket. I would like to know how to leave these values variable, since I can use Buckets in other regions and with other names.

package main


import (
"bytes"
"encoding/csv"
"log"
"net/http"
"os"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
)

const (
    S3_REGION = "sa-east-1"
    S3_BUCKET = "teste-csv"
)

var data = [][]string{{"Line1", "Hello Readers of"}, {"Line2", "golangcode.com"}}

func main() {
    file, err := os.Create("result.csv")
    checkError("Cannot create file", err)
    defer file.Close()

    writer := csv.NewWriter(file)
    defer writer.Flush()

    for _, value := range data {
        err := writer.Write(value)
        checkError("Cannot write to file", err)
    }


    s, err := session.NewSession(&aws.Config{Region: aws.String(S3_REGION)})
    if err != nil {
        log.Fatal(err)
    }

    err = AddFileToS3(s, "result.csv")
    if err != nil {
        log.Fatal(err)
    }
}

func checkError(message string, err error) {
    if err != nil {
        log.Fatal(message, err)
    }
}


    file, err := os.Open(fileDir)
    if err != nil {
        return err
    }
    defer file.Close()

    fileInfo, _ := file.Stat()
    var size int64 = fileInfo.Size()
    buffer := make([]byte, size)
    file.Read(buffer)

    // of the file you're uploading.
    _, err = s3.New(s).PutObject(&s3.PutObjectInput{
        Bucket:               aws.String(S3_BUCKET),
        Key:                  aws.String(fileDir),
        ACL:                  aws.String("private"),
        Body:                 bytes.NewReader(buffer),
        ContentLength:        aws.Int64(size),
        ContentType:          aws.String(http.DetectContentType(buffer)),
        ContentDisposition:   aws.String("attachment"),
        ServerSideEncryption: aws.String("AES256"),
    })
    return err
}

2 answers

0

As said the RFL, you can switch from constant to variable and change the value in the code. There is another method, if the code is the same for other regions and Buckets, you can receive these values by argument const ( S3_REGION = os.Args[1] S3_BUCKET = os.Args[2] ) And when running the executable just put after the name seu.exe sa-east-1 teste-csv. Here is an example of Go by Example, there’s not much of a secret.

0

just change the keyword const for var, this way you will be able to exchange the values contained in the variables, see in more detail in official documentation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.