How to use cookies in the Gin framework (session control)

Reference address

Set and get Cookie | Gin Web Framework (gin-gonic.com)icon-default.png?t=N7T8https://gin-gonic.com/zh-cn /docs/examples/cookie/

What are cookies

Cookies can be found everywhere on the Internet, specifically as follows:

Keep me logged in

Save browser history

Big data can be configured as you wish, and messages can be pushed according to your preferences.

Shopping website add to shopping cart

Cookies are used to save some information;

Introduction to Cookies

  • HTTP is a stateless protocol. The server cannot record the browser’s access status, which means that the server cannot distinguish whether two requests are issued by the same client.
  • HTTP
    It is a stateless protocol. Simply put, when you browse one page and then go to another page on the same website

    In this regard, the server cannot recognize that this is the same browser accessing the same website. Every time I visit, there is nothing

    Relationship. If we want to share data between multiple pages, we can use
    Cookies
    or
    Session
    Reality

    now

  • A cookie is stored in the browser of the visitor’s computer. It allows us to use the same browser to access the same domain name

    when sharing data.

Purpose of Cookies

  • The test server sends a cookie to the client, and the client carries the cookie when making a request.

Set Cookie

Set-Cookie adds a Set-Cookie header to the ResponseWriter’s headers. The cookie provided must have a valid name. Invalid cookies may be deleted silently.

ctx.SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

first parameter
key

second parameter
value

The third parameter expiration time
.
If you just want to set
Cookies
To save the path without setting the survival time, you can pass nil in the third parameter.

The fourth parameter
cookies
path of

The fifth parameter
cookies
path of
Domain
Scope Local debugging is configured as
localhost,
Officially launched and configured as a domain name

The sixth parameter is
secure
,when
secure
The value is
true
hour,
cookies
exist
HTTP
is invalid in
HTTPS
Only effective

The seventh parameter
httpOnly
, Microsoft’s response to
COOKIE
Do the extension. if in
COOKIE
set in
“httpOnly”
Attributes, through the program (JS
script,
applet
etc.) will not be able to read
COOKIE
information, prevent
XSS
attack generated

Get Cookie

cookie, err := ctx.Cookie(“name”)

1. Practical drill (setting and obtaining cookies)

1. Controller settings

package test

import (
"fmt"
"gindemo04/models"
"net/http"

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

type ModelTest struct{}
//That is, there is a controller that sets cookies, and there is a controller that retrieves cookies (get the set first and then retrieve it to get the value)
func (con ModelTest) Index(c *gin.Context) {
//Set cookie
c.SetCookie("username", "Emiya Shirou", 3600, "/", "localhost", false, true)
fmt.Println(models.UnixToTime(1757814260))
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "model test content--conversion timestamp---as follows:",
"t": 1757814260,
})
}
func (con ModelTest) News(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
delay ,_:=c.Cookie("delay")
c.String(http.StatusOK, "cookie=%v,delay=%v",username,delay)
}

func (con ModelTest) Gouwu(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
c.String(http.StatusOK, "cookie=" + username)
}

2. Routing configuration

package routers

import (
"gindemo04/controllers/test"

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

func DefaultRouters(r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", test.ModelTest{}.Index)
defaultRouters.GET("/news", test.ModelTest{}.News)
defaultRouters.GET("/gouwu", test.ModelTest{}.Gouwu)
\t\t
}
}

3. Test

Note: For convenience, the port of main.go is set to 80.

1. Go to setcookie first

2. Test the cookie again

2. Deleting cookies

It can be set as follows:

1. Configure the controller as follows

package test

import (
"fmt"
"gindemo04/models"
"net/http"

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

type ModelTest struct{}
//That is, there is a controller that sets cookies, and there is a controller that retrieves cookies (first get the set and then get the value)
func (con ModelTest) Index(c *gin.Context) {
//Set cookie
c.SetCookie("username", "Emiya Shirou", 3600, "/", "localhost", false, true)
//Expired cookie settings
c.SetCookie("delay", "Expired Demo", 3, "/", "localhost", false, true)

fmt.Println(models.UnixToTime(1757814260))
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "model test content--conversion timestamp---as follows:",
"t": 1757814260,
})
}
func (con ModelTest) News(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
delay ,_:=c.Cookie("delay")
c.String(http.StatusOK, "cookie=%v,delay=%v",username,delay)
}

func (con ModelTest) Gouwu(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
c.String(http.StatusOK, "cookie=" + username)
}

func (con ModelTest) Deletcookie(c *gin.Context) {
//Delete cookie
c.SetCookie("username", "Emiya Shirou", -1, "/", "localhost", false, true)
c.String(http.StatusOK, "Deleting cookies is complete, check whether gouwu and news still have cookie values")
}

2. The routing configuration is as follows

package routers

import (
"gindemo04/controllers/test"

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

func DefaultRouters(r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", test.ModelTest{}.Index)
defaultRouters.GET("/news", test.ModelTest{}.News)
defaultRouters.GET("/gouwu", test.ModelTest{}.Gouwu)
defaultRouters.GET("/deletcookie", test.ModelTest{}.Deletcookie)
}
}

3. Test

If I check gouwu again, there will be no cookies.

3. Operation of expired cookies

Setup time is shorter

package test

import (
"fmt"
"gindemo04/models"
"net/http"

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

type ModelTest struct{}
//That is, there is a controller that sets cookies, and there is a controller that retrieves cookies (first get the set and then get the value)
func (con ModelTest) Index(c *gin.Context) {
//Set cookie
c.SetCookie("username", "Emiya Shirou", 3600, "/", "localhost", false, true)
//Expired cookie settings
c.SetCookie("delay", "Expired Demo", 5, "/", "localhost", false, true)
//Second-level domain name cookie sharing (after logging into Baidu with your Lenovo Baidu account, you can use Baidu Weather to view the weather in your favorite regions)
fmt.Println(models.UnixToTime(1757814260))
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "model test content--conversion timestamp---as follows:",
"t": 1757814260,
})
}
func (con ModelTest) News(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
delay ,_:=c.Cookie("delay")
c.String(http.StatusOK, "cookie=%v,delay=%v",username,delay)
}

func (con ModelTest) Gouwu(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
c.String(http.StatusOK, "cookie=" + username)
}

func (con ModelTest) Deletcookie(c *gin.Context) {
//Delete cookies
c.SetCookie("username", "Emiya Shirou", -1, "/", "localhost", false, true)
c.String(http.StatusOK, "Deleting cookies is complete, check whether gouwu and news still have cookie values")
}

1. Test:

Refresh again ,Gone

Sharing cookies with multiple second-level domains

for example:

After logging into Baidu with your Lenovo Baidu account, you can use Baidu Weather to view the weather in your favorite regions.

Resolve a.frank.com and b.frank.com to our server respectively

What we want is that the user sets the cookie information in a.frank.com and then obtains the cookie just set in b.frank.com, which is to realize the sharing of cookies by multiple second-level domain names.

If you operate domain name resolution on this machine, you need to modify the hosts file under C:\Windows\System32\drivers\etc

Finally this is the effect

1. Controller configuration

package test

import (
"fmt"
"gindemo04/models"
"net/http"

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

type ModelTest struct{}
//That is, there is a controller that sets cookies, and there is a controller that retrieves cookies (first get the set and then get the value)
func (con ModelTest) Index(c *gin.Context) {
//Second-level domain name cookie sharing (after logging into Baidu with your Lenovo Baidu account, you can use Baidu Weather to view the weather in your favorite regions)
c.SetCookie("username","Emiya Shirou",3600,"/",".frank.com",false,true)
fmt.Println(models.UnixToTime(1757814260))
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "model test content--conversion timestamp---as follows:",
"t": 1757814260,
})
}
func (con ModelTest) News(c *gin.Context) {
//Get cookies
username,_ := c.Cookie("username")
c.String(http.StatusOK, "cookie=" + username)
}

2. Routing configuration

package routers

import (
"gindemo04/controllers/test"

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

func DefaultRouters(r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", test.ModelTest{}.Index)
defaultRouters.GET("/news", test.ModelTest{}.News)
\t\t
}
}

3. Test whether two franks can share cookies

1. Go to set cookie first

2. Then visit news (two franks)

a.frank.com can

b.frank.com is also available