Skip to content

Commit 4974aa5

Browse files
lidajunlidajun
lidajun
authored and
lidajun
committed
3rd - gorilla/sessions
1 parent 5009f33 commit 4974aa5

File tree

16 files changed

+527
-1
lines changed

16 files changed

+527
-1
lines changed

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,4 +147,6 @@
147147
* [gorilla/schema](https://darjun/github.io/2021/07/22/godailylib/gorilla/schema)
148148
gorilla Web 开发包之表单处理库
149149
* [gorilla/securecookie](https://darjun/github.io/2021/07/22/godailylib/gorilla/schema)
150-
gorilla Web 开发包之安全 cookie 库
150+
gorilla Web 开发包之安全 cookie 库
151+
* [gorilla/sessions](https://darjun/github.io/2021/07/25/godailylib/gorilla/sessions)
152+
gorilla Web 开发包之 session 处理库

gorilla/sessions/auth/main.go

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"github.com/gorilla/handlers"
6+
"github.com/gorilla/mux"
7+
"github.com/gorilla/securecookie"
8+
"github.com/gorilla/sessions"
9+
"html/template"
10+
"log"
11+
"net/http"
12+
"os"
13+
)
14+
15+
type User struct {
16+
Username string
17+
Count int
18+
}
19+
20+
var (
21+
ptTemplate *template.Template
22+
store = sessions.NewFilesystemStore("./", securecookie.GenerateRandomKey(32), securecookie.GenerateRandomKey(32))
23+
)
24+
25+
func GetSessionUser(r *http.Request) *User {
26+
session, _ := store.Get(r, "user")
27+
s, ok := session.Values["user"]
28+
if !ok {
29+
return nil
30+
}
31+
u := &User{}
32+
json.Unmarshal([]byte(s.(string)), u)
33+
return u
34+
}
35+
36+
func SaveSessionUser(w http.ResponseWriter, r *http.Request, u *User) {
37+
session, _ := store.Get(r, "user")
38+
data, _ := json.Marshal(u)
39+
session.Values["user"] = string(data)
40+
store.Save(r, w, session)
41+
}
42+
43+
func HomeHandler(w http.ResponseWriter, r *http.Request) {
44+
u := GetSessionUser(r)
45+
ptTemplate.ExecuteTemplate(w, "home.tpl", u)
46+
}
47+
48+
func Login(w http.ResponseWriter, r *http.Request) {
49+
ptTemplate.ExecuteTemplate(w, "login.tpl", nil)
50+
}
51+
52+
func DoLogin(w http.ResponseWriter, r *http.Request) {
53+
r.ParseForm()
54+
username := r.Form.Get("username")
55+
password := r.Form.Get("password")
56+
if username != "darjun" || password != "handsome" {
57+
http.Redirect(w, r, "/login", http.StatusFound)
58+
return
59+
}
60+
61+
SaveSessionUser(w, r, &User{Username: username})
62+
http.Redirect(w, r, "/", http.StatusFound)
63+
}
64+
65+
func SecretHandler(w http.ResponseWriter, r *http.Request) {
66+
u := GetSessionUser(r)
67+
if u == nil {
68+
http.Redirect(w, r, "/login", http.StatusFound)
69+
return
70+
}
71+
u.Count++
72+
SaveSessionUser(w, r, u)
73+
ptTemplate.ExecuteTemplate(w, "secret.tpl", u)
74+
}
75+
76+
func Logger(h http.Handler) http.Handler {
77+
return handlers.CombinedLoggingHandler(os.Stdout, h)
78+
}
79+
80+
func main() {
81+
r := mux.NewRouter()
82+
r.Use(Logger)
83+
r.HandleFunc("/", HomeHandler)
84+
r.HandleFunc("/secret", SecretHandler)
85+
r.Handle("/login", handlers.MethodHandler{
86+
"GET": http.HandlerFunc(Login),
87+
"POST": http.HandlerFunc(DoLogin),
88+
})
89+
http.Handle("/", r)
90+
log.Fatal(http.ListenAndServe(":8080", nil))
91+
}
92+
93+
func init() {
94+
ptTemplate = template.Must(template.New("").ParseGlob("./tpls/*.tpl"))
95+
}

gorilla/sessions/auth/tpls/home.tpl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Home</title>
8+
</head>
9+
<body>
10+
{{ if . }}
11+
<p>Hi, {{ .Username }}</p><br>
12+
<a href="/secret">Goto secret?</a>
13+
{{ else }}
14+
<p>Hi, stranger</p><br>
15+
<a href="/login">Goto login?</a>
16+
{{ end }}
17+
</body>
18+
</html>

gorilla/sessions/auth/tpls/login.tpl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Login</title>
8+
</head>
9+
<body>
10+
<form action="/login" method="post">
11+
<label>Username:</label>
12+
<input name="username"><br>
13+
<label>Password:</label>
14+
<input name="password" type="password"><br>
15+
<button type="submit">登录</button>
16+
</form>
17+
</body>
18+
</html>

gorilla/sessions/auth/tpls/secret.tpl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<meta http-equiv="X-UA-Compatible" content="IE=edge">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Secret</title>
8+
</head>
9+
<body>
10+
<p>
11+
Lorem ipsum dolor sit amet consectetur adipisicing elit.
12+
Inventore a cumque sunt pariatur nihil doloremque tempore,
13+
consectetur ipsum sapiente id excepturi enim velit,
14+
quis nisi esse doloribus aliquid. Incidunt, dolore.
15+
</p>
16+
<p>You have visited this page {{ .Count }} times.</p>
17+
</body>
18+
</html>

gorilla/sessions/go.mod

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
module github.com/darjun/go-daily-lib/gorilla/sessions
2+
3+
go 1.16
4+
5+
require (
6+
github.com/garyburd/redigo v1.6.2 // indirect
7+
github.com/gorilla/handlers v1.5.1 // indirect
8+
github.com/gorilla/mux v1.8.0 // indirect
9+
github.com/gorilla/sessions v1.2.1 // indirect
10+
gopkg.in/boj/redistore.v1 v1.0.0-20160128113310-fc113767cd6b // indirect
11+
)

gorilla/sessions/go.sum

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ=
2+
github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
3+
github.com/garyburd/redigo v1.6.2 h1:yE/pwKCrbLpLpQICzYTeZ7JsTA/C53wFTJHaEtRqniM=
4+
github.com/garyburd/redigo v1.6.2/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY=
5+
github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4=
6+
github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q=
7+
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
8+
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
9+
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
10+
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
11+
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
12+
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
13+
gopkg.in/boj/redistore.v1 v1.0.0-20160128113310-fc113767cd6b h1:U/Uqd1232+wrnHOvWNaxrNqn/kFnr4yu4blgPtQt0N8=
14+
gopkg.in/boj/redistore.v1 v1.0.0-20160128113310-fc113767cd6b/go.mod h1:fgfIZMlsafAHpspcks2Bul+MWUNw/2dyQmjC2faKjtg=

gorilla/sessions/nginx.conf

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
2+
#user nobody;
3+
worker_processes 1;
4+
5+
#error_log logs/error.log;
6+
#error_log logs/error.log notice;
7+
#error_log logs/error.log info;
8+
9+
#pid logs/nginx.pid;
10+
11+
12+
events {
13+
worker_connections 1024;
14+
}
15+
16+
17+
http {
18+
default_type application/octet-stream;
19+
20+
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
21+
# '$status $body_bytes_sent "$http_referer" '
22+
# '"$http_user_agent" "$http_x_forwarded_for"';
23+
24+
#access_log logs/access.log main;
25+
26+
sendfile on;
27+
#tcp_nopush on;
28+
29+
#keepalive_timeout 0;
30+
keepalive_timeout 65;
31+
32+
#gzip on;
33+
upstream mysvr {
34+
server localhost:8080;
35+
server localhost:8081;
36+
server localhost:8082;
37+
}
38+
39+
40+
server {
41+
listen 80;
42+
server_name localhost;
43+
44+
#charset koi8-r;
45+
46+
#access_log logs/host.access.log main;
47+
48+
location / {
49+
proxy_pass http://mysvr;
50+
}
51+
52+
#error_page 404 /404.html;
53+
54+
# redirect server error pages to the static page /50x.html
55+
#
56+
error_page 500 502 503 504 /50x.html;
57+
location = /50x.html {
58+
root html;
59+
}
60+
61+
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
62+
#
63+
#location ~ \.php$ {
64+
# proxy_pass http://127.0.0.1;
65+
#}
66+
67+
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
68+
#
69+
#location ~ \.php$ {
70+
# root html;
71+
# fastcgi_pass 127.0.0.1:9000;
72+
# fastcgi_index index.php;
73+
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
74+
# include fastcgi_params;
75+
#}
76+
77+
# deny access to .htaccess files, if Apache's document root
78+
# concurs with nginx's one
79+
#
80+
#location ~ /\.ht {
81+
# deny all;
82+
#}
83+
}
84+
85+
86+
# another virtual host using mix of IP-, name-, and port-based configuration
87+
#
88+
#server {
89+
# listen 8000;
90+
# listen somename:8080;
91+
# server_name somename alias another.alias;
92+
93+
# location / {
94+
# root html;
95+
# index index.html index.htm;
96+
# }
97+
#}
98+
99+
100+
# HTTPS server
101+
#
102+
#server {
103+
# listen 443 ssl;
104+
# server_name localhost;
105+
106+
# ssl_certificate cert.pem;
107+
# ssl_certificate_key cert.key;
108+
109+
# ssl_session_cache shared:SSL:1m;
110+
# ssl_session_timeout 5m;
111+
112+
# ssl_ciphers HIGH:!aNULL:!MD5;
113+
# ssl_prefer_server_ciphers on;
114+
115+
# location / {
116+
# root html;
117+
# index index.html index.htm;
118+
# }
119+
#}
120+
include servers/*;
121+
}

0 commit comments

Comments
 (0)