1. cookie
-
HTTP is a stateless protocol, the server can not access the browser's status record, that server can not distinguish between whether to issue two requests from the same client
-
Cookie is to solve the HTTP protocol , one stateless program , Chinese is the meaning of cookies
-
Cookie is actually saved on the server browser for some information. After the browser has cookies, each time a request to the server are transmitted simultaneously sends the information to the server, the server receives the request, it may request this information processing
-
Cookie created by the server and sent to the browser, and ultimately saved by the browser
2. C ookie use
-
Keep the user logged in
-
Jingdong Shopping Cart
3. cookie usage
-
Test server sends cookie to the client, carrying a client requests a cookie
main Package Penalty for Import ( "github.com/gin-gonic/gin" "fmt" ) FUNC main () { // create a route r: = gin.Default () // server to give clients the cookie r.get ( " the cookie ", FUNC (c * gin.Context) { // get the client whether they carry the cookie the cookie, ERR: = c.Cookie (" key_cookie ") //c.Request.Cookie also OK iF ERR = nil {! the cookie = "NotSet" // set the client cookie // maxAge seconds // path cookie directory // domain domain // secure access whether intelligent through HTTPS // httpOnly whether to allow others to get their own cookie via JS c.SetCookie ( "key_cookie", "value_cookie", 60, "/", "localhost", false,true) } fmt.Printf ( "cookie values are:% S \ n-", Cookie) }) r.Run ( ": 8000") }
3.1
main Package Penalty for Import ( "github.com/gin-gonic/gin" "NET / HTTP" ) FUNC AuthMiddleWare () {gin.HandlerFunc return FUNC (c * gin.Context) { // get the client cookie and check if cookie , ERR: = c.Cookie ( "ABC"); ERR == nil { IF Cookie == "123" { c.Next () return } } // returns error c.JSON (http.StatusUnauthorized, gin.H { "error": "ERR"}) // if the authentication fails, no subsequent function calling process c.Abort () return } } FUNC main () { // create a route R & lt: = gin.Default () R & lt. GET ( "/login", func(c *gin.Context) {The Default () // set a cookie c.SetCookie("abc", "123", 60, "/", "localhost", false, true) // 返回信息 c.String(200, "Login success!") }) r.GET("/home", AuthMiddleWare(), func(c *gin.Context) { c.JSON(200, gin.H{"data": "home"}) }) r.Run(":8000") }
Coo 3.2 kie shortcomings
-
Insecure, clear text
-
Increase bandwidth consumption
-
It can be disabled
-
capped cookie
4. session
-
Session can make up Cookie deficiencies, Session must rely on the Cookie can be used to generate a SessionId on C ookie in to the client can
4.1 session middleware
session.go
package session type Session interface { Set(key string, value interface{}) error Get(key string) (interface{}, error) Del(key string) error Save() error }
session_mgr.go
package session // 定义管理者,管理所有session type SessionMgr interface { // 初始化 Init(addr string, options ...string) (err error) CreateSession() (session Session, err error) Get(sessionId string) (session Session, err error) }
memory.go
package session import ( "sync" "errors" ) // 对象 // MemorySeesion设计: // 定义MemorySeesion对象(字段:sessionId、存kv的map,读写锁) // 构造函数,为了获取对象 // Set() // Get() // Del() // Save() type MemorySession struct { sessionId string // 存kv data map[string]interface{} rwlock sync.RWMutex } // 构造函数 func NewMemorySession(id string) *MemorySession { s := &MemorySession{ sessionId: id, data: make(map[string]interface{}, 16), } return s } func (m *MemorySession) Set(key string, value interface{}) (err error) { // 加锁 m.rwlock.Lock() defer m.rwlock.Unlock() // 设置值 m.data[key] = value return } func (m *MemorySession) Get(key string) (value interface{}, err error) { m.rwlock.Lock() defer m.rwlock.Unlock() value, ok := m.data[key] if !ok { err = errors.New("key not exists in session") return } return } func (m *MemorySession) Del(key string) (err error) { m.rwlock.Lock() defer m.rwlock.Unlock() delete(m.data, key) return } func (m *MemorySession) Save(key string) (err error) { return }
memory_session_mgr.go
package session import( "sync" uuid "github.com/satori/go.uuid" ) // MemorySeesionMgr设计: // 定义MemorySeesionMgr对象(字段:存放所有session的map,读写锁) // 构造函数 // Init() // CreateSeesion() // GetSession() // 定义对象 type MemorySeesionMgr struct { sessionMap map[string]Session rwlock sync.RWMutex } // 构造函数 func NewMemorySeesionMgr() SessionMgr { sr := &MemorySeesionMgr{ sessionMap: make(map[string]Session, 1024), } return sr } func (s *MemorySeesionMgr) Init(addr string, options ...string) (err error) { return } func (s *MemorySeesionMgr)CreateSession()(session Session,err error) { s.rwlock.Lock() defer s.rwlock.Unlock() // go get github.com/satori/go.uuid // 用uuid作为sessionId id, err := uuid.NewV4() if err != nil{ return } // 转string sessionId := id.String() // 创建个session session = NewMemorySession(sessionId) return } func (s *MemorySeesionMgr)Get(sessionId string)(session Session,err error) { return }