LoginSignup
6
6

More than 5 years have passed since last update.

AWSのLambdaでS3にアップロードされたファイルをhookで受け取ってファイルの中身を取得する(apex利用)

Posted at

参照URL

s3: https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/with-s3.html
apex: https://github.com/apex/go-apex

コード(ほぼapexに記載されているのでその写経)

config.go
// Ref: https://github.com/apex/go-apex/blob/master/s3/s3.go

// Event represents a S3 event with one or more records.
type Event struct {
    Records []*Record `json:"Records"`
}

// Record represents a single S3 record.
type Record struct {
    EventVersion string    `json:"eventVersion"`
    EventSource  string    `json:"eventSource"`
    AWSRegion    string    `json:"awsRegion"`
    EventTime    time.Time `json:"eventTime"`
    EventName    string    `json:"eventName"`
    UserIdentity struct {
        PrincipalID string `json:"principalId"`
    } `json:"userIdentity"`
    RequestParameters struct {
        SourceIPAddress string `json:"sourceIPAddress"`
    } `json:"requestParameters"`
    S3 struct {
        SchemaVersion   string  `json:"s3SchemaVersion"`
        ConfigurationID string  `json:"configurationId"`
        Bucket          *Bucket `json:"bucket"`
        Object          *Object `json:"object"`
    }
}
s3.go
// ReadS3Object is Load json file uploaded
func ReadS3Object(event Event) []byte {
    bucket := event.Records[0].S3.Bucket.Name
    object := event.Records[0].S3.Object.Key

    svc := s3.New(session.New())

    params := &s3.GetObjectInput{
        Bucket: aws.String(bucket),
        Key:    aws.String(object),
    }

    resp, err := svc.GetObject(params)
    if err != nil {
        log.Fatal(err)
    }

    b, _ := ioutil.ReadAll(resp.Body)

    return b
}
main.go
package main

import (
    "encoding/json"
    "log"

    apex "github.com/apex/go-apex"
)

func main() {

    apex.HandleFunc(func(data json.RawMessage, ctx *apex.Context) (interface{}, error) {

        var e Event

        // Reccieved "data" convert the "e" object which is build by Event structure
        err := json.Unmarshal(data, &e)
        if err != nil {
            log.Fatal(err)
        }

        d := ReadS3Object(e)

        log.Println(string(d))

        return nil, nil
    })
}
6
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6