Use Golang's standard library to build a website--5. Processing cookies

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.