The origin of Cookie

HTTP protocol is stateless, lies the problem.

Stateless means each request is independent, its execution and results of previous requests and subsequent requests are not directly related, it is not limited by the foregoing request directly affect the response, it does not directly affect the back request response situation.

An interesting word to describe the life is only as strike, for the server, each request is new.

State data can be understood as a client and server created in a given session, and that no state to think that these data will not be retained. Session data generated is we need to be saved, that is to "hold." So Cookie is born under such a scenario.

What is Cookie

On the Internet, Cookie actually refers to a small amount of information, is created by the Web server, the data file information stored on the user's computer (client). General network users accustomed to using the plural form of Cookies, refers to certain sites in order to identify the user identity, a Session tracking and data on the user's local terminal storage, and these data are usually encrypted.

Cookie mechanism

Cookie is generated by the server, sent to the User-Agent (usually a browser), the browser will Cookie of key / value is saved to a text file in a directory, it sends a request to the Cookie the same site next server (provided that the browser is set to enable cookie). Cookie names and values ​​may be developed by their own definition of the server so that the server can know whether the user is a legitimate user and the need to re-sign-on, the server can set or read the information contained in Cookies, thereby maintaining the state of the user with the server session .

To summarize Cookie features:

  1. When the browser sends a request automatically Cookie information to previously stored carry the site.
  2. Cookie data server can be set.
  3. Cookie is for a single domain name, Cookie between different domains are independent.
  4. Cookie data can be configured expiration time expired Cookie data will be cleared system.

View Cookie

We use the Chrome browser to open a Web site, open developer tools to view the site Cookie data stored on our computers.

Go Operation Cookie

Standard library net/httpdefined Cookie, which represents a value in the Set-Cookie header in the HTTP request or HTTP response headers Cookie occurring HTTP cookie.

cookies type struct { 
    the Name        String 
    the Value       String 
    the Path        String 
    the Domain      String 
    the Expires time.time 
    RawExpires String 
    // MaxAge = 0 indicates the attribute is not set MaxAge
     // MaxAge <0 indicates immediately delete the cookie, is equivalent to "MaxAge: 0 "
     // MaxAge> 0 indicates the presence MaxAge properties, in seconds 
    MaxAge    int 
    the Secure    BOOL 
    the HttpOnly BOOL 
    raw       String 
    unparsed [] String  // unresolved" properties - value "of the original text 
}

Cookie settings

net/httpIt provides the following SetCookiefunction, which was added in the Set-Cookie header w header field of the HTTP header value cookie.

func SetCookie(w ResponseWriter, cookie *Cookie)

Get Cookie

RequestCookie objects have two methods of obtaining and a method of adding Cookie:

Two Ways of Cookie:

// parse the request and returns all cookie Cookie header set 
FUNC (r * Request) Cookies () [] * Cookie 

// returns the name of the cookie named in the request, if the cookie is not found returns nil, ErrNoCookie. 
FUNC (R & lt * the Request) cookies (name String ) (* cookies, error)

Add method of Cookie:

// addCookie add a cookie to the request. 
func (r * Request) AddCookie ( c * Cookie)

gin frame operation Cookie

import (
    "fmt"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.GET("/cookie", func(c *gin.Context) {
        cookie, err := c.Cookie("gin_cookie") // 获取Cookie
        if err != nil {
            cookie = "NotSet"
            // 设置Cookie
            c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
        }
        fmt.Printf("Cookie value: %s \n", cookie)
    })

    router.Run()
}

Session

The origin of the Session

Although Cookie solved to a certain extent, a "hold" requirements, but due to the 4096 byte maximum support itself Cookie, Cookie and stored in the client itself, may be intercepted or stolen, and therefore there is a need for something new, it support more bytes, and he saved on the server, there is high security. This is Session.

The question is, based on the characteristics of the stateless HTTP protocol, the server does not know the visitor "who." Then the aforementioned Cookie will play the role of bridge.

After the user login is successful, we created a special session and a unique identifier for each user on the server, they correspond. among them:

  • Session is a data structure stored on the server to track the state of the user, this data may be stored in a cluster, database, file;
  • Unique identification is often referred to Session IDbe written to the user of the Cookie.

In this way the user follow-up visits again, the request will automatically carry Cookie data (which includes Session ID), through which the server Session IDwill be able to find the corresponding Session data, also known to the people "who."

In conclusion: Cookie up for the lack HTTP stateless, let the server know to the people "who"; however Cookie in the form of text stored locally, their security is poor; so we can identify the user through different Cookie, corresponding to each user to save a data server for the Session, the Session data can be saved in user specific data.

Further, the above-mentioned fact, Cookie and Session commonality things, not limited to the language and the frame.