-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
96 lines (69 loc) · 1.69 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
var (
// ErrNotParsed is thrown when the json is not parsed
ErrNotParsed = errors.New("error parsed json")
// ErrNotBody is thrown when a body is not provided
ErrNotBody = errors.New("nothing was provided in the HTTP body")
)
//JSON type
type JSON []byte
//APIRequest type
type APIRequest events.APIGatewayProxyRequest
//APIResponse type
type APIResponse events.APIGatewayProxyResponse
//Response struct
type Response struct {
Message string `json:"msg"`
}
//Input struct
type Input struct {
Name string `json:"name"`
}
// Handler is your Lambda function handler
func Handler(request APIRequest) (APIResponse, error) {
log.Printf("Processing Lambda request %s\n", request.RequestContext.RequestID)
if len(request.Body) < 1 {
return throwAPIError(ErrNotBody)
}
//Decoding JSON
var in Input
err := json.Unmarshal(JSON(request.Body), &in)
if err != nil {
return throwAPIError(err)
}
//Coding JSON
msg, err := createResponseJSON("Hello " + in.Name)
if err != nil {
return throwAPIError(err)
}
return APIResponse{
Body: string(msg),
StatusCode: http.StatusOK,
}, nil
}
//Aux func to throw errors
func throwAPIError(err error) (APIResponse, error) {
res, err := createResponseJSON(err.Error())
if err != nil {
return throwAPIError(err)
}
return APIResponse{Body: string(res),
StatusCode: http.StatusBadRequest}, nil
}
//Aux func to create a ResponseJSON
func createResponseJSON(message string) (JSON, error) {
m := Response{message}
msg, err := json.Marshal(m)
return msg, err
}
func main() {
lambda.Start(Handler)
}