GoWeb session control

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 by the client

cookie

Brief introduction

cookie is actually saved on the server browser for some information. After the browser has Cookie, 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

  • type Cookie
type Cookie struct {
    Name       string
    Value      string
    Path       string
    Domain     string
    Expires    time.Time
    RawExpires string
    // MaxAge=0表示未设置Max-Age属性
    // MaxAge<0表示立刻删除该cookie,等价于"Max-Age: 0"
    // MaxAge>0表示存在Max-Age属性,单位是秒
    MaxAge   int
    Secure   bool
    HttpOnly bool
    Raw      string
    Unparsed []string // 未解析的“属性-值”对的原始文本
}

A representative of Cookie Cookie header value appears in the header field value Set-Cookie header in the HTTP header field in a response, or HTTP requests in the HTTP cookie

  • func (*Cookie) String
func (c *Cookie) String() string

String return sequence of the results of the cookie. If only the Name and Value fields can be used for serialization of the HTTP request or HTTP Cookie header reply Set-Cookie header; If another field is set, the result can only be serialized HTTP reply for Set-Cookie header

The operating principle of the cookie

  1. The first time a cookie is created on the server when sending requests to the server
  2. It will be sent to the server-side browser cookie created by way of response header
  3. Later the browser sends a request carrying the cookie
  4. After the obtained server cookie according to information in the cookie to distinguish different users

Create a cookie and sends it to the browser

  1. Create a cookie and sends it to the server browser

Server-side code

package main

import "net/http"

//setCookie 添加Cookie
func setCookie(w http.ResponseWriter, r *http.Request)  {
	//创建Cookie
	cookie := http.Cookie{
		Name: "user",
		Value: "admin",
		HttpOnly: true,
	}
	cookie2 := http.Cookie{
		Name: "user2",
		Value: "admin2",
		HttpOnly: true,
	}
	//将Cookie发送给浏览器
	w.Header().Set("Set-Cookie", cookie.String())
	//添加第二个Cookie
	w.Header().Add("Set-Cookie", cookie2.String())
}
func main() {
	http.HandleFunc("/setCookie", setCookie)
	http.ListenAndServe(":8080", nil)
}

Browser content of the response packets

HTTP/1.1 200 OK
Set-Cookie: user=admin; HttpOnly
Set-Cookie: user2=admin2; HttpOnly
Date: Fri, 03 Apr 2020 06:58:13 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8
  1. In addition to Set and the Add method, go also provides a faster way to set Cookie
  • func SetCookie
func SetCookie(w ResponseWriter, cookie *Cookie)

Add SetCookie w SetCookie header field in the header of the HTTP cookie header value

package main

import "net/http"

//setCookie 添加Cookie
func setCookie(w http.ResponseWriter, r *http.Request)  {
	//创建Cookie
	cookie := http.Cookie{
		Name: "user",
		Value: "admin",
		HttpOnly: true,
	}
	cookie2 := http.Cookie{
		Name: "user2",
		Value: "admin2",
		HttpOnly: true,
	}
	//直接调用http的SetCookie函数设置Cookie
	http.SetCookie(w, &cookie)
	http.SetCookie(w, &cookie2)
}
func main() {
	http.HandleFunc("/setCookie", setCookie)
	http.ListenAndServe(":8080", nil)
}

Read Cookie

Since the transmission request in the Cookie request header, it can be acquired by Cookie Request Header field structure

Processor code

package main

import (
	"fmt"
	"net/http"
)

//setCookie 添加Cookie
func setCookie(w http.ResponseWriter, r *http.Request)  {
	//创建Cookie
	cookie := http.Cookie{
		Name: "user",
		Value: "admin",
		HttpOnly: true,
	}
	cookie2 := http.Cookie{
		Name: "user2",
		Value: "admin2",
		HttpOnly: true,
	}
	//将Cookie发送给浏览器
	//w.Header().Set("Set-Cookie", cookie.String())
	//添加第二个Cookie
	//w.Header().Add("Set-Cookie", cookie2.String())

	//直接调用http的SetCookie函数设置Cookie
	http.SetCookie(w, &cookie)
	http.SetCookie(w, &cookie2)
}

//getCookies 获取Cookie
func getCookies(w http.ResponseWriter, r *http.Request)  {
	//获取请求头中所有的Cookie
	//cookies := r.Header["Cookie"]
	//如果想得到某一个Cookie,可以直接调用Cookie方法
	cookie, _ := r.Cookie("user")
	fmt.Fprintln(w,"得到的Cookie有: ", cookie)
}

func main() {
	http.HandleFunc("/setCookie", setCookie)
	http.HandleFunc("/getCookies", getCookies)
	http.ListenAndServe(":8080", nil)
}

Browser results

user=admin

Set the effective time of Cookie

Cookie default session level, after the browser is closed Cookie will fail, the effective time can be set by Cookie Cookie field structure MaxAge

package main

import (
	"fmt"
	"net/http"
)

//setCookie 添加Cookie
func setCookie(w http.ResponseWriter, r *http.Request)  {
	//创建Cookie
	cookie := http.Cookie{
		Name: "user",
		Value: "admin",
		HttpOnly: true,
		MaxAge: 60,
	}
	cookie2 := http.Cookie{
		Name: "user2",
		Value: "admin2",
		HttpOnly: true,
	}
	//将Cookie发送给浏览器
	//w.Header().Set("Set-Cookie", cookie.String())
	//添加第二个Cookie
	//w.Header().Add("Set-Cookie", cookie2.String())

	//直接调用http的SetCookie函数设置Cookie
	http.SetCookie(w, &cookie)
	http.SetCookie(w, &cookie2)
}

//getCookies 获取Cookie
func getCookies(w http.ResponseWriter, r *http.Request)  {
	//获取请求头中所有的Cookie
	//cookies := r.Header["Cookie"]
	//如果想得到某一个Cookie,可以直接调用Cookie方法
	cookie, _ := r.Cookie("user")
	fmt.Fprintln(w,"得到的Cookie有: ", cookie)
}

func main() {
	http.HandleFunc("/setCookie", setCookie)
	http.HandleFunc("/getCookies", getCookies)
	http.ListenAndServe(":8080", nil)
}

Response message

HTTP/1.1 200 OK
Set-Cookie: user=admin; Max-Age=60; HttpOnly
Set-Cookie: user2=admin2; HttpOnly
Date: Fri, 03 Apr 2020 07:58:49 GMT
Content-Length: 0
Content-Type: text/plain; charset=utf-8

Cookie Use

  • Advertising Recommended
  • Free login

Session

Brief introduction

Use Cookie has a very earth limitation is that if a lot of Cookie, the intangible increase the amount of data transferred client and server side. And because the browser Cookie restrictions on the number, you can not save too much information in the Cookie, so the Session appear

The role of Session is stored on the server side some of the user data, and then delivered to the user a special Cookie, the Cookie Session this corresponds to a server, you can get to save user information Session through it, then you know which the user sends a request

The operating principle of the Session

  1. First create a Session when sending requests to the server, gives it a globally unique ID (may be generated by UUID)
  2. Create a Cookie, Cookie's Value will be set to the value of the Session ID and Cookie sent to the browser
  3. Later browser will send a request to carry Cookie
  4. The server acquires Cookie and its corresponding server's Value found Session, that knows which user the request is issued
Published 116 original articles · won praise 27 · views 10000 +

Guess you like

Origin blog.csdn.net/wuxingge/article/details/105291636