|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/aws/aws-lambda-go/events" |
| 5 | + "github.com/aws/aws-lambda-go/lambda" |
| 6 | + "github.com/aws/aws-sdk-go/aws" |
| 7 | + "github.com/aws/aws-sdk-go/aws/session" |
| 8 | + "github.com/aws/aws-sdk-go/service/dynamodb" |
| 9 | + "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute" |
| 10 | + "github.com/google/uuid" |
| 11 | + |
| 12 | + "encoding/json" |
| 13 | + "fmt" |
| 14 | + "os" |
| 15 | +) |
| 16 | + |
| 17 | +type Item struct { |
| 18 | + Id string `json:"id,omitempty"` |
| 19 | + Title string `json:"title"` |
| 20 | + Details string `json:"details"` |
| 21 | +} |
| 22 | + |
| 23 | +func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) { |
| 24 | + |
| 25 | + // Creating session for client |
| 26 | + sess := session.Must(session.NewSessionWithOptions(session.Options{ |
| 27 | + SharedConfigState: session.SharedConfigEnable, |
| 28 | + })) |
| 29 | + |
| 30 | + // Create DynamoDB client |
| 31 | + svc := dynamodb.New(sess) |
| 32 | + |
| 33 | + itemUuid := uuid.New().String() |
| 34 | + |
| 35 | + fmt.Println("Generated new item uuid:", itemUuid) |
| 36 | + |
| 37 | + itemString := request.Body |
| 38 | + itemStruct := Item{} |
| 39 | + json.Unmarshal([]byte(itemString), &itemStruct) |
| 40 | + |
| 41 | + item := Item{ |
| 42 | + Id: itemUuid, |
| 43 | + Title: itemStruct.Title, |
| 44 | + Details: itemStruct.Details, |
| 45 | + } |
| 46 | + |
| 47 | + av, err := dynamodbattribute.MarshalMap(item) |
| 48 | + if err != nil { |
| 49 | + fmt.Println("Error marshalling item: ", err.Error()) |
| 50 | + return events.APIGatewayProxyResponse{Body: "Yikes", StatusCode: 500}, nil |
| 51 | + } |
| 52 | + |
| 53 | + tableName := os.Getenv("DYNAMODB_TABLE") |
| 54 | + |
| 55 | + fmt.Println("Putting item: %v", av) |
| 56 | + |
| 57 | + input := &dynamodb.PutItemInput{ |
| 58 | + Item: av, |
| 59 | + TableName: aws.String(tableName), |
| 60 | + } |
| 61 | + |
| 62 | + // PutItem request |
| 63 | + _, err = svc.PutItem(input) |
| 64 | + |
| 65 | + // Checking for errors, return error |
| 66 | + if err != nil { |
| 67 | + fmt.Println("Got error calling PutItem: ", err.Error()) |
| 68 | + return events.APIGatewayProxyResponse{Body: "Yikes", StatusCode: 500}, nil |
| 69 | + } |
| 70 | + |
| 71 | + item_marshalled, err := json.Marshal(item) |
| 72 | + |
| 73 | + fmt.Println("Returning item: ", string(item_marshalled)) |
| 74 | + |
| 75 | + //Returning response with AWS Lambda Proxy Response |
| 76 | + return events.APIGatewayProxyResponse{Body: string(item_marshalled), StatusCode: 200}, nil |
| 77 | +} |
| 78 | + |
| 79 | +func main() { |
| 80 | + lambda.Start(Handler) |
| 81 | +} |
0 commit comments