-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
72 lines (56 loc) · 1.5 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
package main
import "net/http"
//gistsnip:start:server
type Server struct {
comments *Comments
}
//gistsnip:end:server
func NewServer(comments *Comments) *Server {
return &Server{
comments: comments,
}
}
//gistsnip:start:server
func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
server.HandleList(w, r)
case "/comment":
server.HandleAddComment(w, r)
default:
ShowErrorPage(w, http.StatusNotFound, "Page not found", nil)
}
}
func (server *Server) HandleList(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodGet {
ShowErrorPage(w, http.StatusMethodNotAllowed, "Invalid method", nil)
return
}
comments, err := server.comments.List(ctx)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to access DB", err)
return
}
ShowCommentsPage(w, comments)
}
//gistsnip:end:server
func (server *Server) HandleAddComment(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodPost {
ShowErrorPage(w, http.StatusMethodNotAllowed, "Invalid method", nil)
return
}
if err := r.ParseForm(); err != nil {
ShowErrorPage(w, http.StatusBadRequest, "Unable to parse data", err)
return
}
user := r.Form.Get("user")
comment := r.Form.Get("comment")
err := server.comments.Add(ctx, user, comment)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to add data", err)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}