-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
217 lines (190 loc) · 5.19 KB
/
server.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
//
// Author: Henrique Dias
// Last Modification: 2024-04-09 19:14:01
//
import (
"fmt"
"net/http"
"os/exec"
"path"
"runtime"
"strconv"
"strings"
"text/template"
"time"
)
type App struct {
DefaultEmailTo EmailAddress
MaxNumberAttachs int
MaxAttachsSize int
TemplatesDir string
CacheDir string
PublicDir string
ListenPort int
Debug bool
}
func openUrlInBrowser(url string) error {
var cmd string
var args []string
switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
func (app *App) getForm(w http.ResponseWriter, r *http.Request) {
tpl, err := template.ParseFiles(path.Join(app.TemplatesDir, "form.html"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := tpl.Execute(w, map[string]string{
"NameSender": "",
"EmailSender": "",
"NameTo": app.DefaultEmailTo.Name,
"EmailTo": app.DefaultEmailTo.Address,
"Phone": "",
"Subject": "",
"Message": "",
"Checked": "",
"Disabled": "disabled",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (app *App) getAttachments(w http.ResponseWriter, r *http.Request) {
tpl, err := template.ParseFiles(path.Join(app.TemplatesDir, "attachments.html"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := tpl.Execute(w, map[string]string{
"Header": "Attachment",
"MaxNumberAttachs": strconv.Itoa(app.MaxNumberAttachs),
"MaxAttachsSize": strconv.Itoa(app.MaxAttachsSize),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (app *App) sendMail(w http.ResponseWriter, r *http.Request) {
tpl, err := template.ParseFiles(path.Join(app.TemplatesDir, "alert.html"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// debug
if app.Debug {
for _, formName := range []string{"name_sender", "email_sender", "name_to",
"email_to", "subject", "message", "copy_to_me", "your_consent"} {
fmt.Printf("%s: %s\r\n", formName, r.FormValue(formName))
}
}
// Parse our multipart form, 10 << 20 specifies a maximum
// upload of 10 MB files.
if err := r.ParseMultipartForm(10 << 20); err != nil {
if err := tpl.Execute(w, map[string]string{
"Type": "danger",
"Message": "Error retrieving the attachment!",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
senderContacts := func() string {
if r.FormValue("name_sender") == "" {
r.FormValue("email_to")
}
return fmt.Sprintf("%s <%s>",
r.FormValue("name_sender"),
r.FormValue("email_to"))
}()
if r.FormValue("phone") != "" {
senderContacts += fmt.Sprintf("\r\nPhone: %s", r.FormValue("phone"))
}
toList := []EmailAddress{
{
Name: r.FormValue("name_to"),
Address: r.FormValue("email_to"),
},
}
if strings.EqualFold(r.FormValue("copy_to_me"), "true") {
toList = append(toList, EmailAddress{
Name: r.FormValue("name_sender"),
Address: r.FormValue("email_sender"),
})
}
sm := NewSendMail()
if err := sm.sendMail(
EmailAddress{
Name: app.DefaultEmailTo.Name,
Address: app.DefaultEmailTo.Address,
},
toList,
r.FormValue("subject"),
fmt.Sprintf("From: %s\r\nSender: %s\r\n\r\nMessage:\r\n%s",
"Test Form",
senderContacts,
func() string {
if strings.EqualFold(r.FormValue("your_consent"), "true") {
return fmt.Sprintf("%s\r\n\r\n%s", r.FormValue("message"),
"You have read and accepted the privacy policy concerning the treatment of personal information.")
}
return r.FormValue("message")
}()),
r.MultipartForm.File["attachment"],
); err != nil {
if err := tpl.Execute(w, map[string]string{
"Type": "danger",
"Message": "An error happened while sending the message!",
}); err != nil {
panic(err)
}
}
if err := tpl.Execute(w, map[string]string{
"Type": "success",
"Message": "The email was successfully sent!",
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func NewApp() App {
app := new(App)
app.MaxNumberAttachs = 10
app.MaxAttachsSize = 1024 * 1024 * 10 // 10 MB
app.DefaultEmailTo = EmailAddress{
Name: "Test Form",
Address: "test@example.com", // please replace with true email
}
app.CacheDir = "cache"
app.TemplatesDir = "templates"
app.PublicDir = "public/"
app.ListenPort = 8080
app.Debug = true
return *app
}
func main() {
app := NewApp()
mux := http.NewServeMux()
mux.HandleFunc("/getform", app.getForm)
mux.HandleFunc("/getattachments", app.getAttachments)
mux.HandleFunc("/sendmail", app.sendMail)
mux.Handle("/", http.FileServer(http.Dir(app.PublicDir)))
go func() {
<-time.After(100 * time.Millisecond)
openUrlInBrowser(fmt.Sprintf("%s:%d", "http://localhost", app.ListenPort))
}()
server := http.Server{
Addr: fmt.Sprintf(":%d", app.ListenPort),
Handler: mux,
}
fmt.Printf("Server listening on %s", server.Addr)
if err := server.ListenAndServe(); err != nil {
panic(err)
}
}