Skip to content

Commit 536b01c

Browse files
committed
Added POST handler
1 parent 1569d87 commit 536b01c

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

Diff for: main.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,23 @@ func main() {
1616
})
1717
templates = template.Must(template.ParseGlob("templates/*.html"))
1818
r := mux.NewRouter()
19-
r.HandleFunc("/", indexHandler).Methods("GET")
19+
r.HandleFunc("/", indexGetHandler).Methods("GET")
20+
r.HandleFunc("/", indexPostHandler).Methods("POST")
2021
http.Handle("/", r)
2122
http.ListenAndServe(":8080", nil)
2223
}
2324

24-
func indexHandler(w http.ResponseWriter, r *http.Request) {
25+
func indexGetHandler(w http.ResponseWriter, r *http.Request) {
2526
comments, err := client.LRange("comments", 0, 10).Result()
2627
if err != nil {
2728
return
2829
}
2930
templates.ExecuteTemplate(w, "index.html", comments)
3031
}
32+
33+
func indexPostHandler(w http.ResponseWriter, r *http.Request) {
34+
r.ParseForm()
35+
comment := r.PostForm.Get("comment")
36+
client.LPush("comments", comment)
37+
http.Redirect(w, r, "/", 302)
38+
}

Diff for: templates/index.html

+6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
</head>
55
<body>
66
<h1>Comments</h1>
7+
<form method="POST">
8+
<textarea name="comment"></textarea>
9+
<div>
10+
<button type="submit">Post Comment</button>
11+
</div>
12+
</form>
713
{{ range . }}
814
<div>{{ . }}</div>
915
{{ end }}

0 commit comments

Comments
 (0)