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:
Read the Cookie and make the appropriate feedback username, err: = R.cookie ("username") FMT. PRINTLN (username, err)ifErr! = Nil {fmt. Println ("No Cookie", err)}//To determine if a cookie has been setifUsername = = Nil {//Set Cookies Tnow:= Time. Now ()//Set cookies, valid for one yearCookie: =http. Cookie{name:"username", Value:"BCL", Expires:Tnow. Adddate (1,0,0)}http. Setcookie (W, &cookie)}Else{data["visited"] ="Welcome back."+ username. Value}
Run, let's run a look at the effect:
First time visit:
Second visit