@@ -19,8 +19,8 @@ func main() {
1919 })
2020 templates = template .Must (template .ParseGlob ("templates/*.html" ))
2121 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" )
2424 r .HandleFunc ("/login" , loginGetHandler ).Methods ("GET" )
2525 r .HandleFunc ("/login" , loginPostHandler ).Methods ("POST" )
2626 r .HandleFunc ("/register" , registerGetHandler ).Methods ("GET" )
@@ -31,13 +31,19 @@ func main() {
3131 http .ListenAndServe (":8080" , nil )
3232}
3333
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 )
4043 }
44+ }
45+
46+ func indexGetHandler (w http.ResponseWriter , r * http.Request ) {
4147 comments , err := client .LRange ("comments" , 0 , 10 ).Result ()
4248 if err != nil {
4349 w .WriteHeader (http .StatusInternalServerError )
0 commit comments