Web 开发中须要作好用户在整个浏览过程的控制,由于 HTTP 协议是无状态的,因此用户的每一次请求都是无状态的,服务器不知道在整个 Web 操做过程当中哪些链接与该用户有关,应该如何来解决这个问题呢?Web 里面经典的解决方案是 cookie 和 session,cookie 机制是一种客户端机制,把用户数据保存在客户端,而 session 机制是一种服务器端的机制,服务器使用一种相似于散列表的结构来保存信息,每个网站访客都会被分配给一个惟一的标志符,即 sessionID,它的存放形式无非两种:要么通过 url 传递,要么保存在客户端的 cookies 里。固然,你也能够将 Session 保存到数据库里,这样会更安全,但效率方面会有所降低。html
Cookie 是由浏览器维持的,存储在客户端的一小段文本信息,伴随着用户请求和页面在 Web 服务器和浏览器之间传递。用户每次访问站点时,Web 应用程序均可以读取 cookie 包含的信息。web
cookie 是有时间限制的,根据生命期不一样分红两种:redis
会话 cookie
若是不设置过时时间,则表示这个 cookie 生命周期为从建立到浏览器关闭为止,只要关闭浏览器窗口,cookie 就消失了。这种生命期为浏览会话期的 cookie 被称为会话 cookie。会话 cookie 通常不保存在硬盘上而是保存在内存里。sql
持久 cookie
若是设置了过时时间,浏览器就会把 cookie 保存到硬盘上,关闭后再次打开浏览器,这些 cookie 依然有效直到超过设定的过时时间。存储在硬盘上的 cookie 能够在不一样的浏览器进程间共享,好比两个 IE 窗口。而对于保存在内存的 cookie,不一样的浏览器有不一样的处理方式。数据库
设置 cookie:浏览器
Go 语言中经过 net/http 包中的 SetCookie 来设置:安全
http.SetCookie(w ResponseWriter, cookie *Cookie)
复制代码
w 表示须要写入的 response,cookie 是一个 struct,以下:bash
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
复制代码
读取 cookie:服务器
cookie, _ := r.Cookie("NameKey")
或
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
复制代码
示例:
CookieBasic.gocookie
package main
import (
"fmt"
"log"
"net/http"
"time"
)
/*
读写 Cookie
当客户端第一次访问服务端时,服务端为客户端发一个凭证(全局惟一的字符串)
服务端将字符串发给客户端(写Cookie的过程)
HTTP 请求头(发送给服务端Cookie)
HTTP 响应头(在服务端通知客户端保存Cookie)
*/
// 写 cookie
func writeCookie(w http.ResponseWriter, r *http.Request) {
expiration := time.Now()
expiration = expiration.AddDate(0, 0, 3)
cookie := http.Cookie{Name:"username", Value:"geekori", Expires:expiration}
http.SetCookie(w, &cookie)
fmt.Fprintf(w,"write cookie success")
}
// 读 cookie
func readCookie(w http.ResponseWriter, r *http.Request) {
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)
}
func main() {
http.HandleFunc("/writeCookie", writeCookie)
http.HandleFunc("/readCookie", readCookie)
fmt.Println("服务器已经启动,写 cookie 地址:http://localhost:8800/writeCookie ,读 cookie 地址:http://localhost:8800/readCookie")
// 启动 HTTP 服务,并监听端口号,开始监听,处理请求,返回响应
err := http.ListenAndServe(":8800", nil)
if err != nil {
log.Fatal("ListenAndServe",err)
}
}
复制代码
执行以上程序后,服务器控制台输出:
服务器已经启动,写 cookie 地址:http://localhost:8800/writeCookie ,读 cookie 地址:http://localhost:8800/readCookie
复制代码
在浏览器先访问写 cookie 页面,页面显示:write cookie success,经过浏览器能够查看该 cookie,而后访问读 cookie 页面,页面显示:username=geekori。
MultiCookie.go
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"time"
)
// 写 cookies
func writeCookies(w http.ResponseWriter, r *http.Request) {
var cookies map[string]interface{}
cookies = make(map[string]interface{})
cookies["name"] = "Bill"
cookies["age"] = 18
cookies["salary"] = 2000
cookies["country"] = "China"
expiration := time.Now()
expiration = expiration.AddDate(0, 0, 3)
for key,value := range cookies {
v,yes := value.(string)
// 转化失败
if !yes {
var intV = value.(int)
v = strconv.Itoa(intV)
}
cookie := http.Cookie{Name:key, Value:v, Expires:expiration}
http.SetCookie(w, &cookie)
}
fmt.Fprintf(w,"write cookies success")
}
// 读 cookies
func readCookies(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<html>")
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
fmt.Fprint(w, "=")
fmt.Fprint(w, cookie.Value)
fmt.Fprint(w, "<br />")
}
fmt.Fprint(w, "</html>")
}
func main() {
http.HandleFunc("/writeCookies", writeCookies)
http.HandleFunc("/readCookies", readCookies)
fmt.Println("服务器已经启动,写 cookie 地址:http://localhost:8800/writeCookies ,读 cookie 地址:http://localhost:8800/readCookies ")
// 启动 HTTP 服务,并监听端口号,开始监听,处理请求,返回响应
err := http.ListenAndServe(":8800", nil)
if err != nil {
log.Fatal("ListenAndServe",err)
}
}
复制代码
执行以上程序后,服务器控制台输出:
服务器已经启动,写 cookie 地址:http://localhost:8800/writeCookies ,读 cookie 地址:http://localhost:8800/readCookies
复制代码
在浏览器先访问写 cookie 页面,页面显示:write cookies success,经过浏览器能够查看该 cookie,而后访问读 cookie 页面,页面显示:age=18 salary=2000 country=China name=Bill 。
CNCookie.go
package main
import (
"encoding/base64"
"fmt"
"log"
"net/http"
"time"
)
// 写 cookies
func writeCNCookies(w http.ResponseWriter, r *http.Request) {
var cookies map[string]string
cookies = make(map[string]string)
cookies["name"] = "张三"
cookies["country"] = "中国"
expiration := time.Now()
expiration = expiration.AddDate(0, 0, 3)
for key,value := range cookies {
bvalue := []byte(value)
encodeString := base64.StdEncoding.EncodeToString(bvalue)
cookie := http.Cookie{Name:key, Value:encodeString, Expires:expiration}
http.SetCookie(w, &cookie)
}
fmt.Fprintf(w,"write cookies success")
}
// 读 cookies
func readCNCookies(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<html>")
for _, cookie := range r.Cookies() {
if cookie.Name != "name" && cookie.Name != "country" {
continue
}
fmt.Fprint(w, cookie.Name)
fmt.Fprint(w, "=")
decodeBytes,_ := base64.StdEncoding.DecodeString(cookie.Value)
value := string(decodeBytes)
fmt.Fprint(w, value)
fmt.Fprint(w, "<br />")
}
fmt.Fprint(w, "</html>")
}
func main() {
http.HandleFunc("/writeCNCookies", writeCNCookies)
http.HandleFunc("/readCNCookies", readCNCookies)
fmt.Println("服务器已经启动,写 cookie 地址:http://localhost:8800/writeCNCookies ,读 cookie 地址:http://localhost:8800/readCNCookies ")
// 启动 HTTP 服务,并监听端口号,开始监听,处理请求,返回响应
err := http.ListenAndServe(":8800", nil)
if err != nil {
log.Fatal("ListenAndServe",err)
}
}
复制代码
执行以上程序后,服务器控制台输出:
服务器已经启动,写 cookie 地址:http://localhost:8800/writeCNCookies ,读 cookie 地址:http://localhost:8800/readCNCookies
复制代码
在浏览器先访问写 cookie 页面,页面显示:write cookies success,经过浏览器能够查看该 cookie,而后访问读 cookie 页面,页面显示:country=中国 name=张三 。
Seesion 是服务器端开辟的一块内存空间,存放着客户端浏览器窗口的编号,用来记录用户的状态,存放方式依然是名值对。
目前 Go 标准包没有为 session 提供任何支持,须要本身动手来实现 go 版本的 session 管理和建立。
session 的基本原理是由服务器为每一个会话维护一份信息数据,客户端和服务端依靠一个全局惟一的标识来访问这份数据,以达到交互的目的。当用户访问 Web 应用时,服务端程序会随须要建立 session,这个过程能够归纳为三个步骤:
以上三个步骤中,最关键的是如何发送这个 session 的惟一标识这一步上。考虑到 HTTP 协议的定义,数据无非能够放到请求行、头域或 Body 里,因此通常来讲会有两种经常使用的方式:cookie 和 URL 重写。
如下是结合 session 的生命周期(lifecycle),来实现 go 语言版本的 session 管理。
关于 session 管理的整个设计思路以及相应的 go 代码示例:
Session 管理器
定义一个全局的 session 管理器
type Manager struct {
cookieName string //private cookiename
lock sync.Mutex // protects session
provider Provider
maxlifetime int64
}
func NewManager(provideName, cookieName string, maxlifetime int64) (*Manager, error) {
provider, ok := provides[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
return &Manager{provider: provider, cookieName: cookieName, maxlifetime: maxlifetime}, nil
}
复制代码
Go 实现整个的流程应该也是这样的,在 main 包中建立一个全局的 session 管理器
var globalSessions *session.Manager
//而后在init函数中初始化
func init() {
globalSessions, _ = NewManager("memory","gosessionid",3600)
}
复制代码
session 是保存在服务器端的数据,它能够以任何的方式存储,好比存储在内存、数据库或者文件中。所以抽象出一个 Provider 接口,用以表征 session 管理器底层存储结构。
type Provider interface {
SessionInit(sid string) (Session, error)
SessionRead(sid string) (Session, error)
SessionDestroy(sid string) error
SessionGC(maxLifeTime int64)
}
复制代码
那么 Session 接口须要实现什么样的功能呢?有过 Web 开发经验的读者知道,对于 Session 的处理基本就 设置值、读取值、删除值以及获取当前 sessionID 这四个操做,因此咱们的 Session 接口也就实现这四个操做。
type Session interface {
Set(key, value interface{}) error //set session value
Get(key interface{}) interface{} //get session value
Delete(key interface{}) error //delete session value
SessionID() string //back current sessionID
}
复制代码
以上设计思路来源于 database/sql/driver,先定义好接口,而后具体的存储 session 的结构实现相应的接口并注册后,相应功能这样就可使用了,如下是用来随需注册存储 session 的结构的 Register 函数的实现。
var provides = make(map[string]Provider)
// Register makes a session provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, provider Provider) {
if provider == nil {
panic("session: Register provide is nil")
}
if _, dup := provides[name]; dup {
panic("session: Register called twice for provide " + name)
}
provides[name] = provider
}
复制代码
全局惟一的 Session ID
Session ID 是用来识别访问 Web 应用的每个用户,所以必须保证它是全局惟一的(GUID),下面代码展现了如何知足这一需求:
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
复制代码
session 建立
咱们须要为每一个来访用户分配或获取与它相关连的 Session,以便后面根据 Session 信息来验证操做。SessionStart 这个函数就是用来检测是否已经有某个 Session 与当前来访用户发生了关联,若是没有则建立之。
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
sid := manager.sessionId()
session, _ = manager.provider.SessionInit(sid)
cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxlifetime)}
http.SetCookie(w, &cookie)
} else {
sid, _ := url.QueryUnescape(cookie.Value)
session, _ = manager.provider.SessionRead(sid)
}
return
}
复制代码
操做值:设置、读取和删除
SessionStart 函数返回的是一个知足 Session 接口的变量,那么咱们该如何用他来对 session 数据进行操做呢? 如下是相关的操做:
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 {
ct = 1
} else {
ct = ct.(int) + 1
}
sess.Set("countnum", ct)
t, _ := template.ParseFiles("./src/session/count.html")
t.Execute(w, ct)
w.Header().Set("Content-Type", "text/html")
}
复制代码
经过上面的例子能够看到,Session 的操做和操做 key/value 数据库相似:Set、Get、Delete等操做
由于 Session 有过时的概念,因此咱们定义了 GC 操做,当访问过时时间知足 GC 的触发条件后将会引发 GC,可是当咱们进行了任意一个 session 操做,都会对Session实体进行更新,都会触发对最后访问时间的修改,这样当 GC 的时候就不会误删除还在使用的 Session 实体。
session 重置
在 Web 应用中有用户退出这个操做,那么当用户退出应用的时候,须要对该用户的 session 数据进行销毁操做。
//Destroy sessionid
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
return
} else {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: manager.cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
复制代码
session 销毁
Session 管理器如何来管理销毁,只要咱们在 Main 启动的时候启动:
func init() {
go globalSessions.GC()
}
func (manager *Manager) GC() {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionGC(manager.maxlifetime)
time.AfterFunc(time.Duration(manager.maxlifetime), func() { manager.GC() })
}
复制代码
以上 GC 充分利用了 time 包中的定时器功能,当超时 maxLifeTime 以后调用 GC 函数,这样就能够保证 maxLifeTime 时间内的 session 都是可用的,相似的方案也能够用于统计在线用户数之类的。
示例:
SessionDemo.go
package main
import (
"fmt"
"log"
"math/rand"
"net/http"
"strconv"
"time"
)
// 产生指定长度的随机字符串
func generateRandomStr(n int) string {
var strarr = [62]string{}
result := ""
// 填充 0 到 9
for i:=0; i < 10; i++ {
strarr[i] = strconv.Itoa(i)
}
// 填充 a 到 z
for i := 0; i < 26; i++ {
strarr[i + 10] = string(i+97)
}
// 填充 A 到 Z
for i := 0; i < 26; i++ {
strarr[36+i] = string(i + 65)
}
source := rand.NewSource(time.Now().Unix())
r := rand.New(source)
for i := 0; i < n; i++ {
index := r.Intn(len(strarr))
result = result + strarr[index]
}
return result
}
var sessions map[string]string
func writeSessionID(w http.ResponseWriter) {
sessionId := generateRandomStr(20)
sessions[sessionId] = generateRandomStr(100)
expiration := time.Now()
expiration = expiration.AddDate(0,0,40)
cookie := http.Cookie{Name:"mysession_id",Value:sessionId,Expires:expiration}
http.SetCookie(w,&cookie)
}
func mysession(w http.ResponseWriter, r *http.Request) {
cookie,err := r.Cookie("mysession_id")
// 该用户已经提交了 sessionID
if err == nil {
// 校验 SessionID
data,exist := sessions[cookie.Value]
// 服务端存在这个 SessionID,说明用户不是第一次访问服务端
if exist {
fmt.Fprint(w,"该用户已经访问过服务器了:" + data)
} else {
// 须要从新产生 SessionID
writeSessionID(w)
fmt.Fprint(w,"该用户第一次访问服务器")
}
} else {
// 须要从新生产 SessionID
writeSessionID(w)
fmt.Fprint(w,"该用户第一次访问服务器")
}
}
func main() {
sessions = make(map[string]string)
http.HandleFunc("/",mysession)
fmt.Println("服务器已经启动,请在浏览器地址栏中输入:http://localhost:8800")
// 启动 HTTP 服务,并监听端口号,开始监听,处理请求,返回响应
err := http.ListenAndServe(":8800", nil)
if err != nil {
log.Fatal("ListenAndServe",err)
}
}
复制代码
以上代码实现逻辑:
执行以上程序后,服务器控制台输出:
服务器已经启动,请在浏览器地址栏中输入:http://localhost:8800
复制代码
首次访问页面显示:“该用户第一次访问服务器”,刷新页面后显示:该用户已经访问过服务器了:mR7jYg3X8R10CXGAuNLwFb97jP9tPgKGSnwOE6eg0cIrWygfUk3RvbLvnNRrk0UnkFczuXGqdIAN17VyiMwBIre9izpgymRsLCNe。
/goweb/src/session/src/session_library/MySession.go
package geekori_session
import (
"fmt"
"time"
"container/list"
"sync"
"encoding/base64"
"math/rand"
"net/http"
"net/url"
)
var pder = &Provider{list: list.New()}
func GetSession() *Provider {
return pder
}
type SessionStore struct {
sid string //session id惟一标示
timeAccessed time.Time //最后访问时间
value map[interface{}]interface{} //session里面存储的值
}
type Provider struct {
lock sync.Mutex //用来锁
sessions map[string]*list.Element //用来存储在内存
list *list.List //用来作gc
}
func (this *SessionStore) Set(key, value interface{}) error {
this.value[key] = value
pder.SessionUpdate(this.sid)
return nil
}
func (this *SessionStore) Get(key interface{}) interface{} {
pder.SessionUpdate(this.sid)
if v, ok := this.value[key]; ok {
return v
} else {
return nil
}
}
func (this *SessionStore) Delete(key interface{}) error {
delete(this.value, key)
pder.SessionUpdate(this.sid)
return nil
}
func (st *SessionStore) SessionID() string {
return st.sid
}
func (pder *Provider) SessionInit(sid string) (*SessionStore, error) {
pder.lock.Lock()
defer pder.lock.Unlock()
v := make(map[interface{}]interface{}, 0)
newsess := &SessionStore{sid: sid, timeAccessed: time.Now(), value: v}
element := pder.list.PushBack(newsess)
pder.sessions[sid] = element
return newsess, nil
}
func (pder *Provider) SessionRead(sid string) (*SessionStore, error) {
if element, ok := pder.sessions[sid]; ok {
return element.Value.(*SessionStore), nil
} else {
sess, err := pder.SessionInit(sid)
return sess, err
}
return nil, nil
}
func (pder *Provider) SessionDestroy(sid string) error {
if element, ok := pder.sessions[sid]; ok {
delete(pder.sessions, sid)
pder.list.Remove(element)
return nil
}
return nil
}
func (pder *Provider) SessionGC(maxlifetime int64) {
pder.lock.Lock()
defer pder.lock.Unlock()
for {
element := pder.list.Back()
if element == nil {
break
}
if (element.Value.(*SessionStore).timeAccessed.Unix() + maxlifetime) < time.Now().Unix() {
pder.list.Remove(element)
delete(pder.sessions, element.Value.(*SessionStore).sid)
} else {
break
}
}
}
func (this *Provider) SessionUpdate(sid string) error {
this.lock.Lock()
defer this.lock.Unlock()
if element, ok := this.sessions[sid]; ok {
element.Value.(*SessionStore).timeAccessed = time.Now()
this.list.MoveToFront(element)
return nil
}
return nil
}
func init() {
pder.sessions = make(map[string]*list.Element, 0)
Register("memory", pder)
}
var providers = make(map[string]*Provider)
type Manager struct {
cookieName string // Cookie名称
lock sync.Mutex // 同步锁
provider *Provider
maxLifeTime int64
}
type Session interface {
Set(key, value interface{}) error // set session value
Get(key interface{}) interface{} // get session value
Delete(key interface{}) error // delete session value
SessionID() string // back current sessionID
}
func NewManager(provideName, cookieName string, maxLifeTime int64) (*Manager, error) {
provider, ok := providers[provideName]
if !ok {
return nil, fmt.Errorf("session: unknown provide %q (forgotten import?)", provideName)
}
return &Manager{provider: provider, cookieName: cookieName, maxLifeTime: maxLifeTime}, nil
}
func Register(name string, provider *Provider) {
if provider == nil {
panic("session: Register provider is nil")
}
if _, dup := providers[name]; dup {
panic("session: Register called twice for provider " + name)
}
providers[name] = provider
}
func (manager *Manager) sessionId() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return ""
}
return base64.URLEncoding.EncodeToString(b)
}
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
manager.lock.Lock()
defer manager.lock.Unlock()
cookie, err := r.Cookie(manager.cookieName)
// 第一次访问服务端,尚未生成Session
if err != nil || cookie.Value == "" {
// 获取Session ID
sid := manager.sessionId()
// 初始化Session
session, _ = manager.provider.SessionInit(sid)
// 建立Cookie对象,并将session id保存到Cookie对象中
cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, MaxAge: int(manager.maxLifeTime)}
// 向客户端写入包含Session ID的
http.SetCookie(w, &cookie)
} else { // Session已经找到
// 获取Session ID
sid, _ := url.QueryUnescape(cookie.Value)
// 找到Session对象
session, _ = manager.provider.SessionRead(sid)
}
return
}
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
cookie, err := r.Cookie(manager.cookieName)
if err != nil || cookie.Value == "" {
return
} else {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionDestroy(cookie.Value)
expiration := time.Now()
cookie := http.Cookie{Name: manager.cookieName, Path: "/", HttpOnly: true, Expires: expiration, MaxAge: -1}
http.SetCookie(w, &cookie)
}
}
func (manager *Manager) GC() {
manager.lock.Lock()
defer manager.lock.Unlock()
manager.provider.SessionGC(manager.maxLifeTime)
time.AfterFunc(time.Duration(manager.maxLifeTime), func() { manager.GC() })
}
复制代码
/goweb/src/session/TestSession.go
package main
import (
"net/http"
"fmt"
"log"
"session_library"
"time"
"html/template"
)
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 {
ct = 1
} else {
ct = ct.(int) + 1
}
sess.Set("countnum", ct)
t, _ := template.ParseFiles("./src/session/count.html")
t.Execute(w, ct)
w.Header().Set("Content-Type", "text/html")
}
var globalSessions *geekori_session.Manager
func init() {
// redis
globalSessions, _ = geekori_session.NewManager("memory", "gosessionid", 3600)
// goroutine,检测Session是否到期
go globalSessions.GC()
}
func main() {
http.HandleFunc("/count", count) //设置访问的路由
fmt.Println("服务器已经启动,请在浏览器地址栏中输入 http://localhost:8800/count")
err := http.ListenAndServe(":8800", nil) //设置监听的端口
fmt.Println("监听以后")
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
复制代码
/goweb/src/session/count.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计数器</title>
</head>
<body>
<h1>
计数器:{{ . }}
</h1>
</body>
</html>
复制代码
执行以上程序后,服务器控制台输出:
服务器已经启动,请在浏览器地址栏中输入 http://localhost:8800/count
复制代码
访问 count 的页面,显示: “计数器:1”,刷新页面会作计数累加。关闭浏览器后从新打开也会继续累加。
session 劫持是一种普遍存在的比较严重的安全威胁,在 session 技术中,客户端和服务端经过 session 的标识符来维护会话, 但这个标识符很容易就能被嗅探到,从而被其余人利用,它是中间人攻击的一种类型。
session 劫持防范措施:
cookieonly 和 token
如何有效的防止 session 劫持呢?
其中一个解决方案就是 sessionID 的值只容许 cookie 设置,而不是经过 URL 重置方式设置,同时设置 cookie 的 httponly 为 true,这个属性能够设置是否可经过客户端脚本访问这个设置的 cookie,第一这样能够防止这个 cookie 被 XSS 读取从而引发 session 劫持,第二 cookie 设置不会像 URL 重置方式那么容易获取 sessionID。
第二步就是在每一个请求里面加上 token,实现相似前面章节里面讲的防止 form 重复递交相似的功能,咱们在每一个请求里面加上一个隐藏的 token,而后每次验证这个 token,从而保证用户的请求都是惟一性。
h := md5.New()
salt:="astaxie%^7&8888"
io.WriteString(h,salt+time.Now().String())
token:=fmt.Sprintf("%x",h.Sum(nil))
if r.Form["token"]!=token{
//提示登陆
}
sess.Set("token",token)
复制代码
间隔生成新的 SID
还有一个解决方案就是,给 session 额外设置一个建立时间的值,一旦过了必定的时间,就销毁这个 sessionID,从新生成新的 session,这样能够必定程度上防止 session 劫持的问题。
createtime := sess.Get("createtime")
if createtime == nil {
sess.Set("createtime", time.Now().Unix())
} else if (createtime.(int64) + 60) < (time.Now().Unix()) {
globalSessions.SessionDestroy(w, r)
sess = globalSessions.SessionStart(w, r)
}
复制代码
session 启动后,设置了一个值,用于记录生成 sessionID 的时间。经过判断每次请求是否过时(这里设置了60秒)按期生成新的 ID,这样使得攻击者获取有效 sessionID 的机会大大下降。
上面两个手段的组合能够在实践中消除 session 劫持的风险,一方面, 因为 sessionID 频繁改变,使攻击者难有机会获取有效的 sessionID;另外一方面,由于 sessionID 只能在 cookie 中传递,而后设置了 httponly,因此基于 URL 攻击的可能性为零,同时被 XSS 获取 sessionID 也不可能。最后,因为咱们还设置了 MaxAge=0,这样就至关于 session cookie 不会留在浏览器的历史记录里面。