Skip to main content

Cookie/Session

A Cookie is data stored in the browser that is sent along with requests in the request header. It is typically used to store session IDs, tokens, and other data.

func (c *Controller) Cookie(req *ghttp.Request) {
req.Cookie.Set("id", "kslfjojklcjkldjfsie")
req.Cookie.Set("user_name", "诸葛青")

name := req.Cookie.Get("user_name")
req.Response.Writeln("name from cookie: " + name.String())

req.Cookie.Remove("id")
}

The Session mechanism is used to identify which user made a request, and session data is stored on the server.

Previously used for storing login data and performing login verification, it is now mainly used in smaller projects where frontend and backend are not separated.

func (c *Controller) Session(req *ghttp.Request) {
op := req.GetQuery("op").String()
if op == "set" {
req.Session.Set("user", g.Map{"name": "张三", "id": 18})
} else if op == "get" {
req.Response.Writeln(req.Session.Get("user"))
} else if op == "rm" {
req.Session.Remove("user")
}
}