@@ -3,11 +3,13 @@ package main
3
3
import (
4
4
"net/http"
5
5
"github.com/gorilla/mux"
6
+ "github.com/gorilla/sessions"
6
7
"github.com/go-redis/redis"
7
8
"html/template"
8
9
)
9
10
10
11
var client * redis.Client
12
+ var store = sessions .NewCookieStore ([]byte ("t0p-s3cr3t" ))
11
13
var templates * template.Template
12
14
13
15
func main () {
@@ -18,6 +20,9 @@ func main() {
18
20
r := mux .NewRouter ()
19
21
r .HandleFunc ("/" , indexGetHandler ).Methods ("GET" )
20
22
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" )
21
26
fs := http .FileServer (http .Dir ("./static/" ))
22
27
r .PathPrefix ("/static/" ).Handler (http .StripPrefix ("/static/" , fs ))
23
28
http .Handle ("/" , r )
@@ -38,3 +43,28 @@ func indexPostHandler(w http.ResponseWriter, r *http.Request) {
38
43
client .LPush ("comments" , comment )
39
44
http .Redirect (w , r , "/" , 302 )
40
45
}
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