Golang's http cookie usage
Golang's http cookie usage
During server program development, cookies are often used to verify user logon. Golang'snet/http
The http cookie is defined in the package. The following describes the general usage and precautions of the cookie.
Http cookie Definition
Let's take a look at golang's definition of cookie struct:
type Cookie struct { Name string Value string Path string // optional Domain string // optional Expires time.Time // optional RawExpires string // for reading cookies only // 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}
Common parameters:
Name
: Cookie name
Value
: Cookie name value
Domain
: Cookie Scope
Expires
: Set the cookie expiration time
HttpOnly
: Sets the httpOnly attribute (Note: HttpOnly attribute of the Cookie, indicating that the browser should not expose the Cookie in addition to HTTP (and HTTPS) requests. A Cookie with the HttpOnly attribute cannot be accessed in non-HTTP mode, for example, by calling JavaScript (for example, referencing document. therefore, it is impossible to steal this cookie through cross-origin scripts (a very common attack technology. In particular, Facebook and Google are widely using HttpOnly attributes .)
Secure
: Set the Secure attribute (Note: The Secure attribute of the Cookie means that Cookie communication is only restricted to encrypted transmission, indicating that the browser can use the Cookie only through Secure/encrypted connections. If a Web server sets a Cookie with the secure attribute from a non-secure connection, when the Cookie is sent to the client, it can still be intercepted through man-in-the-middle attacks)
MaxAge
: Set the expiration time, corresponding to the MaxAge attribute of the browser cookie
Set cookie on the server side
We can set the cookie attributes on the server.
COOKIE_MAX_MAX_AGE = time. Hour * 24/time. Second // unit: seconds. MaxAge = int (COOKIE_MAX_MAX_AGE) uid: = "10" uid_cookie: = & http. cookie {Name: "uid", Value: uid, Path: "/", HttpOnly: false, MaxAge: maxAge} http. setCookie (c. writer, uid_cookie)
Cookie recorded by the browser
The server obtains the cookie.
var c = *gin.Contextuid, err := c.Request.Cookie("uid")