Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading files from AWS S3 in Golang

I am trying to deploy a golang code on Heroku. My code needs a text file as input and I need to fetch this text file from S3 bucket. My go-code takes the filename as input, Can someone provide a code snippet for reading a file from S3 and storing its contents into a file?

My GOlang code-

  func getDomains(path string) (lines []string, Error error) {

    file, err := os.Open(path)
    if err != nil {
        log.Fatalln(err)
    }

    defer file.Close()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }

    return lines, scanner.Err()
}

func Process(w http.ResponseWriter, r *http.Request) {


    urls := make(chan *Http, Threads*10)
    list, err := getDomains("**NEED A TEXT FILE FROM S3 HERE as an argument**")
    if err != nil {
        log.Fatalln(err)
    }

    var wg sync.WaitGroup
    for i := 0; i < Threads; i++ {
        wg.Add(1)
        go func() {
            for url := range urls {
                url.DNS()
            }

            wg.Done()
        }()
    }

    for i := 0; i < len(list); i++ {
        Progress := fmt.Sprintln(w, len(list))
        urls <- &Http{Url: list[i], Num: Progress}
    }

    close(urls)

    wg.Wait()

    fmt.Printf("\r%s", strings.Repeat(" ", 100))
    fmt.Fprintln(w, "\rTask completed.\n")
}

Can someone suggest a good library for reading the file from S3 into a text file? I cannot download the file from S3 because I have to deploy it on Heroku.

A code snippet for example will be highly appreciated!

like image 497
user3710436 Avatar asked Mar 13 '18 21:03

user3710436


2 Answers

The code snippet below should work (given that you have installed the proper dependencies):

    package main

    import (
        "github.com/aws/aws-sdk-go/aws"
        "github.com/aws/aws-sdk-go/aws/session"
        "github.com/aws/aws-sdk-go/service/s3"
        "github.com/aws/aws-sdk-go/service/s3/s3manager"

        "fmt"
        "log"
        "os"
    )

    func main() {
        // NOTE: you need to store your AWS credentials in ~/.aws/credentials

        // 1) Define your bucket and item names
        bucket := "<YOUR_BUCKET_NAME>"
        item   := "<YOUR_ITEM_NAME>"

        // 2) Create an AWS session
        sess, _ := session.NewSession(&aws.Config{
                Region: aws.String("us-west-2")},
        )

        // 3) Create a new AWS S3 downloader 
        downloader := s3manager.NewDownloader(sess)


        // 4) Download the item from the bucket. If an error occurs, log it and exit. Otherwise, notify the user that the download succeeded.
        file, err := os.Create(item)
        numBytes, err := downloader.Download(file,
            &s3.GetObjectInput{
                Bucket: aws.String(bucket),
                Key:    aws.String(item),
        })

        if err != nil {
            log.Fatalf("Unable to download item %q, %v", item, err)
        }

        fmt.Println("Downloaded", file.Name(), numBytes, "bytes")

    }

For more details you can check the AWS Go SDK and the Github Example

like image 199
Ammar Mohammed Avatar answered Sep 20 '22 12:09

Ammar Mohammed


Using current stable AWS lib for go:

sess := session.Must(session.NewSession(&aws.Config{
    ....
    }))


svc := s3.New(sess)

rawObject, err := svc.GetObject(
                &s3.GetObjectInput{
                    Bucket: aws.String("toto"),
                    Key:    aws.String("toto.txt"),
                })

buf := new(bytes.Buffer)
buf.ReadFrom(rawObject.Body)
myFileContentAsString := buf.String()
like image 31
Thomas Decaux Avatar answered Sep 20 '22 12:09

Thomas Decaux