-
Notifications
You must be signed in to change notification settings - Fork 0
/
email-collector.go
93 lines (85 loc) · 2.57 KB
/
email-collector.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
package main // import "github.com/productionwentdown/email-collector"
import (
"bytes"
"encoding/csv"
"encoding/json"
"flag"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
// modified from @badoux's checkmail
"github.com/productionwentdown/email-collector/checkmail"
)
var filename string
var listen string
var redirect string
var slack string
func main() {
flag.StringVar(&filename, "file", "list.csv", "file to append records to")
flag.StringVar(&listen, "listen", ":8080", "address to listen to")
flag.StringVar(&redirect, "redirect", "/subscribed", "path to redirect to upon success")
flag.StringVar(&slack, "slack", "", "optional slack webhook url")
flag.Parse()
csvMutex := &sync.Mutex{}
csvFile, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer csvFile.Close()
if err != nil {
log.Fatal(err)
}
csvWriter := csv.NewWriter(csvFile)
http.HandleFunc("/subscribe", func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
email := r.Form.Get("email")
if err := checkmail.ValidateFormat(email); err != nil {
log.Println(email, err)
http.Error(w, "Email is not valid", http.StatusBadRequest)
return
}
err = checkmail.ValidateHost(email)
if _, ok := err.(checkmail.SmtpError); !ok && err != nil {
log.Println(email, err)
http.Error(w, "Email is not valid", http.StatusBadRequest)
return
}
log.Println(email, "success")
csvMutex.Lock()
csvWriter.Write([]string{email, time.Now().String()})
csvWriter.Flush()
csvMutex.Unlock()
if len(slack) > 4 {
object := map[string]string{
"text": "A human (" + email + ") subscribed to the list! Wohoo!",
}
payload, err := json.Marshal(object)
if err != nil {
log.Println("json.Marshal failed, not supposed to happen!")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
resp, err := http.Post(slack, "application/json", bytes.NewBuffer(payload))
if err != nil {
log.Println(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
log.Println(body)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
w.Header().Add("Location", redirect)
w.WriteHeader(303)
})
log.Fatal(http.ListenAndServe(listen, nil))
}