-
Notifications
You must be signed in to change notification settings - Fork 48
/
http-session.go
62 lines (52 loc) · 1.4 KB
/
http-session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/sessions"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
var store *sessions.CookieStore
func init() {
store = sessions.NewCookieStore([]byte("secret-key"))
}
func home(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
var authenticated interface{} = session.Values["authenticated"]
if authenticated != nil {
isAuthenticated := session.Values["authenticated"].(bool)
if !isAuthenticated {
http.Error(w, "You are unauthorized to view the page", http.StatusForbidden)
return
}
fmt.Fprintln(w, "Home Page")
} else {
http.Error(w, "You are unauthorized to view the page", http.StatusForbidden)
return
}
}
func login(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
session.Values["authenticated"] = true
session.Save(r, w)
fmt.Fprintln(w, "You have successfully logged in.")
}
func logout(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session-name")
session.Values["authenticated"] = false
session.Save(r, w)
fmt.Fprintln(w, "You have successfully logged out.")
}
func main() {
http.HandleFunc("/home", home)
http.HandleFunc("/login", login)
http.HandleFunc("/logout", logout)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil {
log.Fatal("error starting http server : ", err)
return
}
}