Skip to content

Commit 430448f

Browse files
committed
Added sessions
1 parent 78dc320 commit 430448f

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

Diff for: main.go

+30
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ package main
33
import (
44
"net/http"
55
"github.com/gorilla/mux"
6+
"github.com/gorilla/sessions"
67
"github.com/go-redis/redis"
78
"html/template"
89
)
910

1011
var client *redis.Client
12+
var store = sessions.NewCookieStore([]byte("t0p-s3cr3t"))
1113
var templates *template.Template
1214

1315
func main() {
@@ -18,6 +20,9 @@ func main() {
1820
r := mux.NewRouter()
1921
r.HandleFunc("/", indexGetHandler).Methods("GET")
2022
r.HandleFunc("/", indexPostHandler).Methods("POST")
23+
r.HandleFunc("/login", loginGetHandler).Methods("GET")
24+
r.HandleFunc("/login", loginPostHandler).Methods("POST")
25+
r.HandleFunc("/test", testGetHandler).Methods("GET")
2126
fs := http.FileServer(http.Dir("./static/"))
2227
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
2328
http.Handle("/", r)
@@ -38,3 +43,28 @@ func indexPostHandler(w http.ResponseWriter, r *http.Request) {
3843
client.LPush("comments", comment)
3944
http.Redirect(w, r, "/", 302)
4045
}
46+
47+
func loginGetHandler(w http.ResponseWriter, r *http.Request) {
48+
templates.ExecuteTemplate(w, "login.html", nil)
49+
}
50+
51+
func loginPostHandler(w http.ResponseWriter, r *http.Request) {
52+
r.ParseForm()
53+
username := r.PostForm.Get("username")
54+
session, _ := store.Get(r, "session")
55+
session.Values["username"] = username
56+
session.Save(r, w)
57+
}
58+
59+
func testGetHandler(w http.ResponseWriter, r *http.Request) {
60+
session, _ := store.Get(r, "session")
61+
untyped, ok := session.Values["username"]
62+
if !ok {
63+
return
64+
}
65+
username, ok := untyped.(string)
66+
if !ok {
67+
return
68+
}
69+
w.Write([]byte(username))
70+
}

Diff for: templates/login.html

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<html>
2+
<head>
3+
<title>Login</title>
4+
</head>
5+
<body>
6+
<form method="POST">
7+
Username: <input name="username">
8+
<div>
9+
<button type="submit">Login</button>
10+
</div>
11+
</form>
12+
</body>
13+
</html>

0 commit comments

Comments
 (0)