generated from bitfield/habit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
88 lines (75 loc) · 1.88 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
package habit
import (
"errors"
"fmt"
"log"
"net/http"
)
type server struct {
*http.Server
controller *Controller
}
//NewServer returns a new server
func NewServer(controller *Controller, address string) (*server, error) {
if controller == nil {
return nil, errors.New("controller cannot be nil")
}
if address == "" {
return nil, errors.New("address cannot be empty")
}
server := server{
Server: &http.Server{
Addr: address},
controller: controller,
}
return &server, nil
}
//Run listens and serves http
func (server *server) Run() {
router := server.Routes()
server.Handler = router
err := server.ListenAndServe()
if err != http.ErrServerClosed {
log.Println(err)
}
}
//Routes returns a http.Handler with the appropriate routes
func (server *server) Routes() http.Handler {
router := http.NewServeMux()
router.HandleFunc("/", server.HandleIndex())
router.HandleFunc("/all", server.HandleAll())
return router
}
//HandleIndex handler that servers habits.
func (server *server) HandleIndex() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
//parsing querystring
habitName := r.FormValue("habit")
if habitName == "" || r.URL.Path != "/" {
http.Error(w, "cannot parse querystring", http.StatusBadRequest)
return
}
frequency := r.FormValue("frequency")
if frequency == "" {
frequency = "daily" //default frequency
}
inputHabit, err := parseHabit(habitName, frequency)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
h, err := server.controller.Handle(inputHabit)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
fmt.Fprint(w, h)
}
}
//HandleAll handler that serves /all
func (server *server) HandleAll() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
allHabits := server.controller.GetAllHabits()
fmt.Fprint(w, allHabits)
}
}