/
web.go
48 lines (40 loc) · 1.19 KB
/
web.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
package main
import (
"fmt"
"log"
"net/http"
"net/mail"
"strings"
)
func rootHandler(w http.ResponseWriter, r *http.Request) {
RootTemplate.Execute(w, nil)
}
func InsertHandler(w http.ResponseWriter, r *http.Request) {
var newSubscriber mail.Address
newSubscriber.Name = r.FormValue("Name")
newSubscriber.Address = r.FormValue("Email-id")
if newSubscriber.Address == "" {
fmt.Fprintf(w, "Sorry the email field cannot be left empty")
} else if isPresent(newSubscriber.Address) == true {
fmt.Fprintf(w, "Sorry the email address is already taken")
} else {
AddSubscriber(newSubscriber)
fmt.Fprintf(w, "You have succesfully subscribed")
}
}
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "You have succesfully unsubscribed")
unsub := strings.TrimPrefix(r.URL.String(), "/unsubscribe/")
FindAndRemove(unsub)
}
func WebServer(host string, port int) {
addr := fmt.Sprintf("%s:%d", host, port)
http.HandleFunc("/subscribe", InsertHandler)
http.HandleFunc("/unsubscribe/", DeleteHandler)
http.HandleFunc("/", rootHandler)
log.Println("Starting web interface at", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
log.Fatal("ERROR:", err)
}
}