/
get.go
100 lines (86 loc) · 2.66 KB
/
get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"aws-restful-api/device"
"encoding/json"
"net/http"
"os"
"strings"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
)
var dynamoDBSvc dynamodbiface.DynamoDBAPI
func init() {
sess := session.Must(session.NewSessionWithOptions(session.Options{SharedConfigState: session.SharedConfigEnable}))
dynamoDBSvc = dynamodb.New(sess)
}
func GetDevice(deviceId string, dynamoIfaceSvc dynamodbiface.DynamoDBAPI) (*dynamodb.GetItemOutput, error) {
tableName := aws.String(os.Getenv("TABLE_NAME"))
input := &dynamodb.GetItemInput{
TableName: tableName,
Key: map[string]*dynamodb.AttributeValue{
"id": {
S: aws.String(deviceId),
},
},
}
operOutput, err := dynamoIfaceSvc.GetItem(input)
return operOutput, err
}
func GetHandler(request events.APIGatewayProxyRequest) events.APIGatewayProxyResponse {
if request.HTTPMethod != "GET" {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusBadRequest,
Body: "400 Bad Request: Invalid http method",
}
}
deviceId := ""
splitPath := strings.Split(request.Path, "/")
if len(splitPath) == 4 && strings.HasPrefix(request.Path, "/api/devices/") {
deviceId = splitPath[len(splitPath)-1]
} else {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusForbidden,
Body: "403 Forbidden Access: URL path is incorrect",
}
}
if deviceId == "" {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusBadRequest,
Body: "400 Bad Request: ID of device is missed in path",
}
}
result, err2 := GetDevice(deviceId, dynamoDBSvc)
if err2 != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "500 Internal Server Error: The server encountered an internal error or misconfiguration to connect to database",
}
}
if len(result.Item) == 0 {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusNotFound,
Body: "404 Not Found: Requested item does not exist in the database",
}
}
device := device.Device{}
err2 = dynamodbattribute.UnmarshalMap(result.Item, &device)
if err2 != nil {
return events.APIGatewayProxyResponse{
StatusCode: http.StatusInternalServerError,
Body: "500 Internal Server Error",
}
}
deviceJson, _ := json.Marshal(device)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: string(deviceJson),
}
}
func main() {
lambda.Start(GetHandler)
}