@@ -19,8 +19,8 @@ func main() {
19
19
})
20
20
templates = template .Must (template .ParseGlob ("templates/*.html" ))
21
21
r := mux .NewRouter ()
22
- r .HandleFunc ("/" , indexGetHandler ).Methods ("GET" )
23
- r .HandleFunc ("/" , indexPostHandler ).Methods ("POST" )
22
+ r .HandleFunc ("/" , AuthRequired ( indexGetHandler ) ).Methods ("GET" )
23
+ r .HandleFunc ("/" , AuthRequired ( indexPostHandler ) ).Methods ("POST" )
24
24
r .HandleFunc ("/login" , loginGetHandler ).Methods ("GET" )
25
25
r .HandleFunc ("/login" , loginPostHandler ).Methods ("POST" )
26
26
r .HandleFunc ("/register" , registerGetHandler ).Methods ("GET" )
@@ -31,13 +31,19 @@ func main() {
31
31
http .ListenAndServe (":8080" , nil )
32
32
}
33
33
34
- func indexGetHandler (w http.ResponseWriter , r * http.Request ) {
35
- session , _ := store .Get (r , "session" )
36
- _ , ok := session .Values ["username" ]
37
- if ! ok {
38
- http .Redirect (w , r , "/login" , 302 )
39
- return
34
+ func AuthRequired (handler http.HandlerFunc ) http.HandlerFunc {
35
+ return func (w http.ResponseWriter , r * http.Request ) {
36
+ session , _ := store .Get (r , "session" )
37
+ _ , ok := session .Values ["username" ]
38
+ if ! ok {
39
+ http .Redirect (w , r , "/login" , 302 )
40
+ return
41
+ }
42
+ handler .ServeHTTP (w , r )
40
43
}
44
+ }
45
+
46
+ func indexGetHandler (w http.ResponseWriter , r * http.Request ) {
41
47
comments , err := client .LRange ("comments" , 0 , 10 ).Result ()
42
48
if err != nil {
43
49
w .WriteHeader (http .StatusInternalServerError )
0 commit comments