Use of Golang gin Cookie

Cookie introduction


  • 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.
  • Cookie is one of the solutions to the statelessness of HTTP protocol. Chinese means cookie.
  • A cookie is actually a piece of information stored on the browser by the server. After the browser has a cookie, this information will be sent to the server every time it sends a request to the server. After the server receives the request, it can process the request based on this information.
  • Cookies are created by the server, sent to the browser, and ultimately saved by the browser.

What cookies are used for

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

 

 

Use of cookies


  • Obtaining cookies :

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie provided in the request, or ErrNoCookie if not found. And returns the named cookie unescaped. If multiple cookies match the given name, only one cookie will be returned.

  • Cookie settings :
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

 SetCookie Adds the Set-Cookie header to the ResponseWriter's headers . The cookie provided must have a valid name. Invalid cookies may be silently discarded.

parameter:

name: the name of the cookie

value: cookie value

maxAge int: cookie survival time, unit is seconds

path: the directory where the cookie is located

domain string: domain name

secure: whether it can only be accessed through https

httpOnly bool: Whether to allow others to obtain their own cookies through js

Example demonstration :

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

func TestHandler(c *gin.Context) {

// 获取客户端是否携带cookie
	if cookie, err := c.Cookie("username"); err != nil {
		fmt.Println("cookie", cookie)
		fmt.Println("err", err)
         
        cookie = "lucas"
        // 给客户端设置cookie
		c.SetCookie("username", cookie, 60*60, "/", "localhost", false, true)

		fmt.Printf("cookie的值为:%v\n", cookie)
		c.String(200, "测试cookie")
	}

}

func main() {
   // 1.创建路由
   // 默认使用了2个中间件Logger(), Recovery()
	engine := gin.Default()

	engine.GET("/cookie", TestHandler)
	engine.Run(":8888")
}

cookie 
err http: named cookie not present
cookie的值为:lucas
[GIN] 2023/09/12 - 18:29:13 | 200 |       924.4µs |             ::1 | GET      "/cookie"

 View cookies

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/132837954