-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
82 lines (66 loc) · 1.64 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
package site
import (
"context"
"net/http"
)
//gistsnip:start:db
type DB interface {
Comments() Comments
}
type Comments interface {
Add(ctx context.Context, user, comment string) error
List(ctx context.Context) ([]Comment, error)
}
type Server struct {
db DB
}
//gistsnip:end:db
func NewServer(db DB) *Server {
return &Server{
db: db,
}
}
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)
}
}
//gistsnip:start:db
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.db.Comments().List(ctx)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to access DB", err)
return
}
ShowCommentsPage(w, comments)
}
//gistsnip:end:db
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.db.Comments().Add(ctx, user, comment)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to add data", err)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
}