-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession-demo.go
94 lines (86 loc) · 2.16 KB
/
session-demo.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// main project main.go
package main
import (
"fmt"
"html/template"
"log"
_ "memory"
"net/http"
"session"
"strings"
"time"
)
func sayHelloName(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println(r.Form)
fmt.Println(r.URL.Path)
fmt.Println(r.URL.Scheme)
fmt.Println(r.Form["url_long"])
for k, v := range r.Form {
fmt.Println("key: ", k)
fmt.Println("value:", strings.Join(v, ""))
}
fmt.Fprintln(w, "hello nihao")
}
func login(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
fmt.Println("method: ", r.Method)
if r.Method == "GET" {
t, err := template.ParseFiles("src/html/login.gtpl")
if err != nil {
fmt.Println(err)
return
}
t.Execute(w, nil)
} else {
fmt.Println("username: ", r.Form["username"])
fmt.Println("password: ", r.Form["password"])
}
}
func login2(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
r.ParseForm()
if r.Method == "GET" {
t, _ := template.ParseFiles("src/html/login.gtpl")
//w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("username"))
} else {
sess.Set("username", r.Form["username"])
http.Redirect(w, r, "/", 302)
}
}
func count(w http.ResponseWriter, r *http.Request) {
sess := globalSessions.SessionStart(w, r)
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 360) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
ct := sess.Get("countnum")
if ct == nil {
sess.Set("countnum", 1)
} else {
sess.Set("countnum", (ct.(int) + 1))
}
t, _ := template.ParseFiles("count.gtpl")
w.Header().Set("Content-Type", "text/html")
t.Execute(w, sess.Get("countnum"))
}
func main() {
//http.HandleFunc("/", sayHelloName);
http.HandleFunc("/login", login)
http.HandleFunc("/login2", login2)
http.HandleFunc("/count", count)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatalf("Listen and server", err)
}
}
var globalSessions *session.Manager
func init() {
globalSessions, _ = session.NewSessionManager("memory", "goSessionid", 3600)
go globalSessions.GC()
fmt.Println("fd")
}