@@ -3,11 +3,13 @@ package main
33import (
44 "net/http"
55 "github.com/gorilla/mux"
6+ "github.com/gorilla/sessions"
67 "github.com/go-redis/redis"
78 "html/template"
89)
910
1011var client * redis.Client
12+ var store = sessions .NewCookieStore ([]byte ("t0p-s3cr3t" ))
1113var templates * template.Template
1214
1315func 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+ }
0 commit comments