This is a creation in Article, where the information may have evolved or changed.
Reasonable use of cookies can greatly improve the user experience of the site, this article is mainly to discuss how to deal with cookies in go.
Statement
The go language is set by the Setcookie in the Net/http package:
To set a method declaration for a cookiehttp.Setcookie(WResponsewriter, Cookies *Cookies)//CookiesThe statementtype Cookiesstruct{Name string Value string Path string Domain string Expires Time. Time Rawexpires string//MaxAge=0means No'Max- Age'attribute specified. //MaxAge<0means Delete Cookies Now,equivalently'Max- Age: 0 '//MaxAge>0means Max- Age attribute present and given inch seconds MaxAge int Secure BOOL HttpOnly BOOL Raw string unparsed[]string//Raw text of unparsed attribute-value Pairs}
How to set the cookie (written in the index method)
tNow := time.Now()cookie := http.Cookie"username""BCL", Expires: tNow.AddDate(100)}http.SetCookie(w, &cookie)
Run it and view the request header in the browser, such as:
The cookie has been successfully set.
Ways to get cookies
The method of obtaining a cookie is also simple:
username, err := r.Cookie("username")
It is important to note that R. The Cookie ("username") does not directly return the value of the username corresponding string type
Instead, a new cookie struct is returned to hold the corresponding value of the username.
Now combine the two steps together to write a complete example of handling cookies:
//读取cookie,并做出相应的反馈username, err := r.Cookie("username")fmt.Println(username, err)if err != nil { fmt.Println("No Cookie", err)} //判断是否已经设置了cookieif username == nil { //设置cookie tNowtime.Now() //设置cookie,有效期为一年 http"username""BCL"tNow.AddDate(100)} httpelse { data["visited""欢迎回来 " + username.Value}
Run, let's run a look at the effect:
First time visit:
Second visit