在Golang中从AWS S3读取文件

时间:2018-03-13 21:58:17

标签: go heroku amazon-s3

我正在尝试在Heroku上部署golang代码。我的代码需要一个文本文件作为输入,我需要从S3存储桶中获取此文本文件。我的go-code将文件名作为输入,有人可以提供一个代码片段,用于从S3读取文件并将其内容存储到文件中吗?

我的GOlang代码 -

  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")
}

有人可以建议一个好的库来读取来自S3的文件到文本文件中吗?我无法从S3下载文件,因为我必须在Heroku上部署它。

例如,代码片段将受到高度赞赏!

3 个答案:

答案 0 :(得分:5)

下面的代码片段应该有效(假设您已经安装了正确的依赖项):

    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")

    }

有关详情,请查看AWS Go SDKGithub Example

答案 1 :(得分:1)

以下是使用SDK的V2版本获取对象的功能(改编自https://github.com/aws/aws-sdk-go-v2中的示例):

注意:没有错误处理-仅演示代码。

package s3demo

import (
    "os"
    "context"
    "fmt"
    "io/ioutil"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/aws/awserr"
    "github.com/aws/aws-sdk-go-v2/aws/external"
    "github.com/aws/aws-sdk-go-v2/service/s3"
)

func GetObjectWithV2SDKDemo() {
    bucket := "YOUR_BUCKET"
    key := "YOUR_OBJECT_KEY"
    fileName := "YOUR_FILE_PATH"

    // may need AWS_PROFILE and AWS_REGION populated as environment variables
    cfg, err := external.LoadDefaultAWSConfig()
    if err != nil {
        panic("failed to load config, " + err.Error())
    }

    svc := s3.New(cfg)
    ctx := context.Background()
    req := svc.GetObjectRequest(&s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    })

    resp, err := req.Send(ctx)
    if err != nil {
        panic(err)
    }

    s3objectBytes, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }
    // create file
    f, err := os.Create(fileName)
    defer f.Close()
    if err != nil {
        panic(err)
    }

    bytesWritten, err := f.Write(s3objectBytes)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Fetched %d bytes for S3Object\n", bytesWritten)
    fmt.Printf("successfully downloaded data from %s/%s\n to file %s", bucket, key, fileName)
} 

答案 2 :(得分:1)

将当前的稳定AWS库用于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()