How does the Gin framework handle sessions

In the Gin framework, we can rely on the gin-contrib/ Sessions middleware to handle sessions.

Storage engines supported by gin-contrib/sessions middleware:

  • cookie
  • memstore
  • redis
  • memcached
  • mongodb

Here’s how to use session

1. Install the Session package

go get github.com/gin-contrib/sessions
Copy the code

2.1 Basic Session Usage

package main

import (
        // Import the session package
	"github.com/gin-contrib/sessions"
       // Import the session storage engine
	"github.com/gin-contrib/sessions/cookie"
        // Import gin framework package
	"github.com/gin-gonic/gin"
)

func main(a) {
	r := gin.Default()
        // To create a cookie-based storage engine, the secret11111 parameter is the key used for encryption
	store := cookie.NewStore([]byte("secret11111"))
        // Set session middleware. Mysession refers to the session name and also the cookie name
       // Store is the storage engine created earlier. We can replace it with another storage engine
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/hello".func(c *gin.Context) {
                // Initialize the session object
		session := sessions.Default(c)
                
                // Use session.Get to read the session value
                // Session is key-value format data, so the data needs to be queried by key
		if session.Get("hello") != "world" {
                        // Set session data
			session.Set("hello"."world")
                        // Delete session data
                        session.Delete("tizi365")
                        // Save session data
			session.Save()
                        // Delete the entire session
                        // session.Clear()
		}
                
		c.JSON(200, gin.H{"hello": session.Get("hello")})
	})
	r.Run(": 8000")}Copy the code

2.2 Session based on Redis storage engine

If we want to save session data to Redis, just change the session storage engine to Redis.

Example of using Redis as a storage engine:

First install the redis storage engine package

go get github.com/gin-contrib/sessions/redis
Copy the code

Example:

package main

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
)

func main(a) {
	r := gin.Default()
	// Initialize the redis-based storage engine
	// Parameter description:
	// The first parameter - redis the maximum number of idle connections
	// The second parameter - number communication protocol TCP or UDP
	-redis address, format, host:port
	// the fourth parameter - redis password
	// The 5th parameter -session encryption key
	store, _ := redis.NewStore(10."tcp"."localhost:6379".""And []byte("secret"))
	r.Use(sessions.Sessions("mysession", store))

	r.GET("/incr".func(c *gin.Context) {
		session := sessions.Default(c)
		var count int
		v := session.Get("count")
		if v == nil {
			count = 0
		} else {
			count = v.(int)
			count++
		}
		session.Set("count", count)
		session.Save()
		c.JSON(200, gin.H{"count": count})
	})
	r.Run(": 8000")}Copy the code

Originally, session is an abstract concept. Developers abstract one-to-one interaction between user agent and server into “session” in order to realize operations such as interruption and continuation, and then derive “session state”, which is the concept of session.

A cookie is an actual thing, a header field defined in the HTTP protocol. Think of it as a back-end stateless implementation of session.

What is a cookie? To take a simple example, when we visit a website these days, we often automatically save our account and password so that we can log in directly the next time we visit. The implementation of this technology is the use of cookie technology. Cookie is a file that stores key-value pairs. It must be remembered that the cookie is added to the response by the server and returned to the client. Then the client will automatically receive the cookie in the response and save it locally. The cookie is appended to the request, and the server iterates through the request’s cookie to see if there is any matching information