-
Notifications
You must be signed in to change notification settings - Fork 2
/
handler.go
114 lines (93 loc) · 2.5 KB
/
handler.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package main
import (
"log"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/service/ses"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/aws"
"os"
"encoding/json"
"errors"
"net/http"
)
var (
EmailNotProvided = errors.New("no email provided")
MessageNotProvided = errors.New("no message provided")
)
const (
Success = "success"
Error = "error"
)
type ClientMessage struct {
Email string `json:"email"`
Name string `json:"name"`
Message string `json:"message"`
}
type ResponseMessage struct {
Type string `json:"type"`
Message string `json:"message"`
}
var toEmail string
var subject string
var emailClient *ses.SES
func init() {
toEmail = os.Getenv("TO_EMAIL")
subject = os.Getenv("SUBJECT")
if len(subject) < 0 {
subject = "Message from website"
}
emailClient = ses.New(session.New(), aws.NewConfig().WithRegion("eu-west-1"))
}
func ReturnErrorToUser(error error, status int) (events.APIGatewayProxyResponse, error) {
errorMessage, _ := json.Marshal(ResponseMessage{
Type: Error,
Message: error.Error(),
})
log.Println(error.Error())
return events.APIGatewayProxyResponse{
Headers: map[string]string{"Content-Type": "application/json"},
StatusCode:status,
Body: string(errorMessage),
}, nil
}
func Handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
body := request.Body
var message ClientMessage
err := json.Unmarshal([]byte(body), &message)
if err != nil {
return ReturnErrorToUser(err, http.StatusInternalServerError)
} else if len(message.Email) < 1 {
return ReturnErrorToUser(EmailNotProvided, http.StatusBadRequest)
} else if len(message.Message) < 1 {
return ReturnErrorToUser(MessageNotProvided, http.StatusBadRequest)
}
emailParams := &ses.SendEmailInput{
Message: &ses.Message{
Body: &ses.Body{
Text: &ses.Content{
Data:aws.String(message.Message + "\n From: " + message.Name + " - " + message.Email),
},
},
Subject: &ses.Content{
Data:aws.String(subject),
},
},
Destination: &ses.Destination{
ToAddresses:[]*string{aws.String(toEmail)},
},
Source:aws.String(toEmail),
}
_, err = emailClient.SendEmail(emailParams)
if err != nil {
return ReturnErrorToUser(err, http.StatusInternalServerError)
}
successResponse, err := json.Marshal(ResponseMessage{Success, "Message is sent"})
return events.APIGatewayProxyResponse{
Body: string(successResponse),
StatusCode: 200,
}, nil
}
func main() {
lambda.Start(Handler)
}