Help us understand the problem. What is going on with this article?

【Go】S3のファイルを取得する方法

環境

  • Go - 1.13

事前準備

aws-sdk-goパッケージを使用するため、go getする。

$ go get -u github.com/aws/aws-sdk-go

サンプルコード

package main

import (
    "bytes"
    "fmt"

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

func main() {
    bucket := "bucket"     // バケット名
    path := "path/to/file" // ファイルパス

    /*
     * アクセスキーID・シークレットアクセスキーを直接指定する場合
     */
    // svc := s3.New(session.New(), &aws.Config{
    //  Region: aws.String("ap-northeast-1"),
    //  Credentials: credentials.NewStaticCredentialsFromCreds(credentials.Value{
    //      // NOTE: GitHub等で公開する場合は環境変数に入れましょう
    //      AccessKeyID:     "xxxxxxxxxxxx",
    //      SecretAccessKey: "xxxxxxxxxxxx",
    //  }),
    // })

    /*
     * ~.aws/credentialsに認証情報が設定済の場合、
     * または、環境変数`AWS_ACCESS_KEY_ID`と`AWS_SECRET_ACCESS_KEY`に値が設定されている場合は、
     * ここではアクセスキーID・シークレットアクセスキーを指定しなくても大丈夫
     */
    svc := s3.New(session.New(), &aws.Config{
        Region: aws.String("ap-northeast-1"),
    })

    obj, _ := svc.GetObject(&s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(path),
    })
    defer obj.Body.Close()

    buf := new(bytes.Buffer)
    buf.ReadFrom(obj.Body)
    rslt := buf.String()

    fmt.Println(rslt)
    // => "ファイルの内容"
}

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away