-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
115 lines (93 loc) · 2.42 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"context"
"log"
"net/http"
"github.com/jackc/pgx/v4/pgxpool"
)
type Comment struct {
User string
Text string
}
func initDatabse(ctx context.Context, db *pgxpool.Pool) error {
_, err := db.Exec(ctx, `
CREATE TABLE IF NOT EXISTS Comments (
"User" TEXT,
"Comment" TEXT
)
`)
return err
}
func addComment(ctx context.Context, db *pgxpool.Pool, user, comment string) error {
_, err := db.Exec(ctx, `INSERT INTO Comments ("User", "Comment") VALUES ($1, $2)`, user, comment)
return err
}
//gistsnip:start:list
func listComments(ctx context.Context, db *pgxpool.Pool) ([]Comment, error) {
rows, err := db.Query(ctx, `SELECT "User", "Comment" FROM Comments`)
if err != nil {
return nil, err
}
defer rows.Close()
comments := []Comment{}
for rows.Next() {
var comment Comment
err := rows.Scan(&comment.User, &comment.Text)
if err != nil {
return nil, err
}
comments = append(comments, comment)
}
if err := rows.Err(); err != nil {
return nil, err
}
return comments, nil
}
func main() {
ctx := context.Background()
db, err := pgxpool.Connect(ctx, "user=dbdemo password=dbdemo dbname=dbdemo sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := initDatabse(ctx, db); err != nil {
log.Fatal(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
ShowErrorPage(w, http.StatusMethodNotAllowed, "Invalid method", nil)
return
}
comments, err := listComments(ctx, db)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to access DB", err)
return
}
ShowCommentsPage(w, comments)
})
//gistsnip:end:list
http.HandleFunc("/comment", func(w http.ResponseWriter, r *http.Request) {
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 := addComment(ctx, db, user, comment)
if err != nil {
ShowErrorPage(w, http.StatusInternalServerError, "Unable to add data", err)
return
}
http.Redirect(w, r, "/", http.StatusSeeOther)
})
log.Println("Started listening on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
//gistsnip:start:list
}
//gistsnip:end:list