/
subscribe.go
41 lines (38 loc) · 961 Bytes
/
subscribe.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
package serves
import (
"fmt"
"net/http"
"net/mail"
)
func (a Serve) SubscribeEmail(w http.ResponseWriter, req *http.Request) {
email := req.URL.Query().Get("email")
if email == "" {
JSONError(w, fmt.Errorf("You must set an email"), http.StatusPreconditionRequired)
return
}
_, err := mail.ParseAddress(email)
if err != nil {
JSONError(w, err, http.StatusBadRequest)
return
}
err = a.store.Subscribe(email)
if err != nil {
JSONError(w, err, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
}
func (a Serve) UnsubscribeEmail(w http.ResponseWriter, req *http.Request) {
email := req.URL.Query().Get("email")
if email == "" {
HTMLError(w, fmt.Errorf("You must set an email"), http.StatusPreconditionRequired)
return
}
err := a.store.Unsubscribe(email)
if err != nil {
HTMLError(w, err, http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("you have successfully unsubscribed"))
}