-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunction.go
127 lines (96 loc) · 2.46 KB
/
function.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
115
116
117
118
119
120
121
122
123
124
125
126
127
package function
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/mailgun/mailgun-go/v3"
)
type Response struct {
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
}
func (r Response) Json(w http.ResponseWriter) {
res, _ := json.Marshal(r)
if _, err := fmt.Fprintf(w, string(res)); err != nil {
panic(err)
}
return
}
func Mail(w http.ResponseWriter, r *http.Request) {
// Set CORS headers for the preflight request
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Origin", os.Getenv("ACCESS_CONTROL_ALLOW_ORIGIN"))
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusNoContent)
return
}
// Set headers for the main request.
w.Header().Set("Access-Control-Allow-Origin", os.Getenv("ACCESS_CONTROL_ALLOW_ORIGIN"))
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusForbidden)
res := Response{
Error: "Wrong Method, only accepting 'POST'",
}
res.Json(w)
return
}
if r.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusBadRequest)
res := Response{
Error: "Wrong Content-Type, only accepting 'application/json'",
}
res.Json(w)
return
}
var d struct {
Email string `json:"email"`
Message string `json:"message"`
}
if err := json.NewDecoder(r.Body).Decode(&d); err != nil {
panic(err)
return
}
if d.Email == "" || d.Message == "" {
w.WriteHeader(http.StatusBadRequest)
res := Response{
Error: "Empty data, 'email' or 'message'",
}
res.Json(w)
return
}
mg := mailgun.NewMailgun(
os.Getenv("MAILGUN_DOMAIN"),
os.Getenv("MAILGUN_API_KEY"),
)
mg.SetAPIBase(os.Getenv("MAILGUN_API_BASE"))
sender := d.Email
subject := os.Getenv("MAIL_SUBJECT")
body := d.Message
recipient := os.Getenv("MAIL_RECIPIENT")
message := mg.NewMessage(sender, subject, body, recipient)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
// Send the message with a 10 second timeout
_, _, err := mg.Send(ctx, message)
if err != nil {
log.Printf("Could not send email: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
res := Response{
Error: err.Error(),
}
res.Json(w)
return
}
w.WriteHeader(http.StatusOK)
res := Response{
Message: "All good cowboy!",
}
res.Json(w)
return
}