Giter Club home page Giter Club logo

aws-sdk-go-wrapper's Introduction

aws-sdk-go-wrapper

GoDoc License: MIT Release Build Status Coveralls Coverage Codecov Coverage Go Report Card Code Climate BCH compliance

Simple wrapper for aws-sdk-go At this time, this library suports these AWS services below,

Service API
CloudTrail LookupEvents
CloudWatch GetMetricStatistics
CostExplorer GetCostAndUsage
DynamoDB BatchWriteItem
CreateTable
DeleteItem
DeleteTable
DescribeTable
GetItem
ListTables
PutItem
Query
UpdateTable
Scan
IAM GetGroup
GetGroupPolicy
GetPolicyVersion
GetRolePolicy
GetUserPolicy
ListEntitiesForPolicy
ListGroups
ListGroupPolicies
ListPolicies
ListUsers
ListUserPolicies
ListRoles
ListRolePolicies
Kinesis CreateStream
DeleteStream
DescribeStream
GetRecords
GetShardIterator
PutRecord
KMS CreateAlias
CreateKey
Decrypt
DescribeKey
Encrypt
ReEncrypt
ReEncrypt
ScheduleKeyDeletion
Pinpoint SendEmail
Rekognition CompareFaces
CreateCollection
DeleteCollection
DeleteFaces
DetectFaces
DetectLabels
DetectModerationLabels
GetCelebrityInfo
IndexFaces
ListCollections
ListFaces
RecognizeCelebrities
SearchFaces
SearchFacesByImage
S3 CreateBucket
CopyObject
DeleteBucket
DeleteObject
GetObject
HeadObject
ListObjectsV2
PutObject
SNS CreatePlatformEndpoint
CreateTopic
DeleteTopic
GetEndpointAttributes
GetPlatformApplicationAttributes
Publish
SetEndpointAttributes
Subscribe
SQS ChangeMessageVisibility
CreateQueue
DeleteMessage
DeleteMessageBatch
DeleteQueue
GetQueueAttributes
GetQueueUrl
ListQueues
PurgeQueue
ReceiveMessage
SendMessageBatch
X-Ray PutTraceSegments

Quick Usage

CloudTrail

import (
    "fmt"
    "time"

    "github.com/evalphobia/aws-sdk-go-wrapper/cloudtrail"
    "github.com/evalphobia/aws-sdk-go-wrapper/config"
)

func main() {
    // Create CloudTrail service
    svc, err := cloudtrail.New(config.Config{
        AccessKey: "access",
        SecretKey: "secret",
        Region: "ap-north-east1",
    })
    if err != nil {
        panic("error to create client")
    }

    // Get all of CloudTrail events with in the time.
    results, err := svc.LookupEventsAll(cloudtrail.LookupEventsInput{
        StartTime: time.Now(),
        EndTime:   time.Now(),
        LookupAttributes: []LookupAttribute{
            {
                Key:   "EventName",
                Value: "GetEndpointAttributes", // sns
            },
        },
    })
    if err != nil {
        panic("error to get table")
    }

    for _, v := results.Events {
        fmt.Printf("%+v\n", v)
    }

DynamoDB

import (
    "github.com/evalphobia/aws-sdk-go-wrapper/config"
    "github.com/evalphobia/aws-sdk-go-wrapper/dynamodb"
)

func main() {
    // Create DynamoDB service
    svc, err := dynamodb.New(config.Config{
        AccessKey: "access",
        SecretKey: "secret",
        Region: "ap-north-east1",
        Endpoint:  "http://localhost:8000", // option for DynamoDB Local
    })
    if err != nil {
        panic("error to create client")
    }

    // Get DynamoDB table
    table, err := svc.GetTable("MyDynamoTable")
    if err != nil {
        panic("error to get table")
    }

    // Create new DynamoDB item (row on RDBMS)
    item := dynamodb.NewPutItem()
    item.AddAttribute("user_id", 999)
    item.AddAttribute("status", 1)

    // Add item to the put spool
    table.AddItem(item)

    item2 := dynamodb.NewItem()
    item.AddAttribute("user_id", 1000)
    item.AddAttribute("status", 2)
    item.AddConditionEQ("status", 3) // Add condition for write
    table.AddItem(item2)

    // Put all items in the put spool
    err = table.Put()

    // Use svc.PutAll() to put all of the tables,
    // `err = svc.PutAll()`

    // Scan items
    cond = table.NewConditionList()
    cond.SetLimit(1000)
    cond.FilterEQ("status", 2)
    result, err = table.ScanWithCondition(cond)
    data := result.ToSliceMap() // `result.ToSliceMap()` returns []map[string]interface{}

    //Scan from last key
    cond.SetStartKey(result.LastEvaluatedKey)
    result, err = table.ScanWithCondition(cond)
    data = append(data, result.ToSliceMap())

    // Query items
    cond := table.NewConditionList()
    cond.AndEQ("user_id", 999)
    cond.FilterLT("age", 20)
    cond.SetLimit(100)
    result, err := table.Query(cond)
    if err != nil {
        panic("error to query")
    }

    // mapping result data to the struct
    type User struct {
        ID int64 `dynamodb:"user_id"`
        Age int `dynamodb:"age"`
        Status int `dynamodb:"status"`
    }
    var list []*User
    err = result.Unmarshal(&list)
    if err != nil {
        panic("error to unmarshal")
    }

    if len(list) == int(result.Count) {
        fmt.Println("success to get items")
    }
}

Kinesis

import(
    "encoding/json"

    "github.com/evalphobia/aws-sdk-go-wrapper/config"
    "github.com/evalphobia/aws-sdk-go-wrapper/kinesis"
)

func main(){
    // Create Kinesis service
    svc, err := kinesis.New(config.Config{
        AccessKey: "access key",
        SecretKey: "access key",
        Region: "ap-north-east1",
    })
    if err != nil {
        panic("error on creating client")
    }

    // Get Kinesis Stream
    stream, err := svc.GetStream("my-stream")
    if err != nil {
        panic("error on getting stream")
    }

    // Get ShardID list of the stream
    shardIDs, err := stream.GetShardIDs()
    if err != nil {
        panic("error on getting shard id")
    }

    // get records from all of the shards
    for _, shardID := range shardIDs {
        // get records
        result, err := stream.GetRecords(kinesis.GetCondition{
            ShardID:           shardID,
            ShardIteratorType: kinesis.IteratorTypeLatest,
        })
        if err != nil {
            panic("error on getting records")
        }

        // get next records from the last result.
        result, err = stream.GetRecords(kinesis.GetCondition{
            ShardID:           shardID,
            ShardIteratorType: kinesis.IteratorTypeLatest,
            ShardIterator:     result.NextShardIterator,
        })
    }

    data := make(map[string]interface{})
    data["foo"] = 999
    data["bar"] = "some important info"

    bytData, _ := json.Marshal(data)

    // put data into stream record
    err = stream.PutRecord(bytData)
    if err != nil {
        panic("error on putting record")
    }
}

S3

import(
    "os"

    "github.com/evalphobia/aws-sdk-go-wrapper/config"
    "github.com/evalphobia/aws-sdk-go-wrapper/s3"
)

func main(){
    // Create S3 service
    svc, err := s3.New(config.Config{
        AccessKey: "access",
        SecretKey: "secret",
        Region: "ap-north-east1",
        S3ForcePathStyle: true,
        Endpoint:  "http://localhost:4567", // option for FakeS3
    })
    if err != nil {
        panic("error to create client")
    }

    bucket := svc.GetBucket("MyBucket")

    // upload file
    var file *os.File
    file = getFile() // dummy code. this expects return data of "*os.File". e.g. from POST form.
    s3obj := s3.NewPutObject(file)
    bucket.AddObject(s3obj, "/foo/bar/new_file")
    err = bucket.PutAll()
    if err != nil {
       panic("error to put file")
    }

    // upload file from text data
    text := "Lorem ipsum"
    s3obj2 := s3.NewPutObjectString(text)
    bucket.AddObject(s3obj2, "/log/new_text.txt")

    // upload file of ACL authenticated-read
    bucket.AddSecretObject(s3obj2, "/secret_path/new_secret_file.txt")

    // put all added objects.
    err = bucket.PutAll() // upload "/log/new_text.txt" & "/secret_path/new_secret_file.txt"
    if err != nil {
       panic("error to put files")
    }

    byt, err := bucket.GetObjectByte("/log/new_text.txt")
    if err != nil {
       panic("error to get file")
    }

    fmt.Println(string(byt)) // => Lorem ipsum
}

SNS

import(
    "fmt"

    "github.com/evalphobia/aws-sdk-go-wrapper/config"
    "github.com/evalphobia/aws-sdk-go-wrapper/sns"
)

func main(){
    svc, err := sns.New(config.Config{
        AccessKey: "access key",
        SecretKey: "access key",
        Region: "ap-north-east1",
    }, Platforms{
        Production: false, // flag for APNS/APNS sandbox.
        Apple:      "arn:aws:sns:us-east-1:0000000000:app/APNS/foo_apns", // Endpoint ARN for APNS
        Google:     "arn:aws:sns:us-east-1:0000000000:app/GCM/foo_gcm", // Endpoint ARN for GCM
    })
    if err != nil {
        panic("error to create client")
    }

    // send message to iOS devices.
    tokenListForIOS := []string{"fooEndpoint"}
    err = svc.BulkPublishByDevice("ios", tokenListForIOS, "push message!")
    if err != nil {
        panic("error to publish")
    }

    // send message to multiple devices.
    tokenList := map[string][]string{
        "android": {"token1", "token2"},
        "ios": {"token3", "token4"},
    }
    err = svc.BulkPublish(tokenList, "push message!")
    if err != nil {
        panic("error to publish")
    }
}

SQS

import(
    "fmt"

    "github.com/evalphobia/aws-sdk-go-wrapper/config"
    "github.com/evalphobia/aws-sdk-go-wrapper/sqs"
)

func main(){
    svc, err := sqs.New(config.Config{
        AccessKey: "access key",
        SecretKey: "access key",
        Region: "ap-north-east1",
    })
    if err != nil {
        panic("error to create client")
    }

    queue := svc.GetQueue("my-queue")

    // add message to spool
    queue.AddMessage("my message")

    // send messages in spool
    err := queue.Send()
    if err != nil {
        panic("error on sending sqs message")
    }

    // count message in SQS Queue
    num, _, _ := queue.CountMessage()
    if num > 0 {
        panic("message count must be sent")
    }

    // fetch messages from SQS Queue
    // maximum 10 message
    messageList, err := queue.Fetch(10)
    if err != nil {
        panic("error on getting sqs message")
    }

    for _, msg := messageList {
        // print message content
        fmt.Println(msg.Body())

        // delete message manually
        // if set queue.AutoDelete(true), messages are delete on fetching process
        queue.DeleteMessage(msg)
    }

    // purge queue
    queue.Purge()
}

License

MIT

aws-sdk-go-wrapper's People

Contributors

antcs avatar bsoo avatar davidgamba avatar evalphobia avatar fukubaka0825 avatar gitter-badger avatar gotokatsuya avatar kentokento avatar makotano avatar mgale avatar narita-takeru avatar ogady avatar t-kurimura avatar yu81 avatar yukkobay avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

aws-sdk-go-wrapper's Issues

[RFC] Versioning aws-sdk-go by go.mod

ref: #56


Background

I have not used versioning in this repository on purpose.
I thought it's better that users can choose the version of aws-sdk-go that they want.
Because,

  1. When this wrapper updates the version, users might test all of logics on their app related to AWS. Even this wrapper only adds methods for SQS, internal aws-sdk-go changes all of services, so users should test not only SQS but also DynamoDB, S3 and so on.
    • This is from my experience of updating the database ORM library. When I changed the ORM, an internal DB library also updated and database connection behavior changed then it affects service.
  2. When a user wants to use latest version of aws-sdk-go,
  3. When a user use Go1.11, Go emits an error if the golang version written in go.mod is newer than Go1.11 (ref: golang/go#30446)

Question

But in most cases, can we solve these issues to use replace in go.mod?

// go.mod

require (
	github.com/aws/aws-sdk-go v1.20.21 // indirect
	github.com/evalphobia/aws-sdk-go-wrapper v1.12.0
)

replace (
	github.com/aws/aws-sdk-go => github.com/aws/aws-sdk-go v1.29.27
)
// main.go

package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/evalphobia/aws-sdk-go-wrapper/s3"
	"github.com/evalphobia/aws-sdk-go-wrapper/config"
)

func main() {
	fmt.Println(aws.SDKVersion) // => should be v1.29.27

	s3.New(config.Config{}) // => also work on v1.29.27?
}

So ...

We don't have any downsides of go.mod thus should we use it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.