forked from trevex/golem_examples
/
example_session.go
74 lines (61 loc) · 1.95 KB
/
example_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
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"flag"
"fmt"
"github.com/gorilla/sessions"
"github.com/trevex/golem"
"log"
"net/http"
)
var addr = flag.String("addr", ":8080", "http service address")
const (
secret = "super-secret-key"
sessionName = "golem.sid"
)
// Create session store.
var store = sessions.NewCookieStore([]byte(secret))
// Handshake callback to validate if request has session and is logged in.
func validateSession(w http.ResponseWriter, r *http.Request) bool {
if session, err := store.Get(r, sessionName); err == nil { // Get session.
if v, ok := session.Values["isAuthorized"]; ok && v == true { // Check if session is authorized.
fmt.Println("Authorized user identified!")
return true
}
}
fmt.Println("Unauthorized user detected!")
return false;
}
// If not available creates session and flags it as authorized.
func loginHandler(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, sessionName)
session.Values["isAuthorized"] = true
session.Save(r, w)
// Redirect back to main page to test websocket connection.
http.Redirect(w, r, "/example_session.html", http.StatusFound)
}
// Flags session as not authorized.
func logoutHandler(w http.ResponseWriter, r *http.Request) {
if session, err := store.Get(r, sessionName); err == nil {
delete(session.Values, "isAuthorized")
session.Save(r, w)
}
// Redirect back to main page to test websocket connection.
http.Redirect(w, r, "/example_session.html", http.StatusFound)
}
func main() {
flag.Parse()
// Create a router
myrouter := golem.NewRouter()
myrouter.OnHandshake(validateSession)
// Serve the public files
http.Handle("/", http.FileServer(http.Dir("./public")))
// Handle login/logout
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/logout", logoutHandler)
// Handle websockets using golems handler
http.HandleFunc("/ws", myrouter.Handler())
// Listen
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}