English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Analysis of Cookie usage in Go language

This article illustrates the usage of cookies in Go language. Share it with everyone for reference, as follows:

Web development inevitably involves dealing with cookies. Go's http library also provides related operations for cookies.

type Cookie struct {
  Name string
  Value string
  Path string
  Domain string
  Expires time.Time
  RawExpires string
  MaxAge int
  Secure bool
  HttpOnly bool
  Raw string
  Unparsed []string
}

The Name field is the name of the cookie, Value is its value, and the remaining Path and Domain are the storage scope of the cookie. Expires is the expiration time of the cookie. If not set, it is a session-type cookie, that is, the browser session is valid, and the cookie will be deleted immediately once the browser is closed.

Set Cookie

cookie is a content of header, so it can use the response's Header method to set cookie.

func setCookieHandler(w http.ResponseWriter, r *http.Request) {
    c1 := http.Cookie{
        Name: "first_cookie",
        Value: "vanyar",
        HttpOnly: true,
    }
    c2 := http.Cookie{
        Name: "second_cookie",
        Value: "noldor",
        HttpOnly: true,
    }
    w.Header().Set("Set-Cookie", c1.String())
    w.Header().Add("Set-Cookie", c2.String())
}

Here, you can also test the difference between the Set and Add methods. Of course, like file upload, Go also provides common utility functions.

http.SetCookie(w, &c1)
http.SetCookie(w, &c2)

The http SetCookie method can also set cookies, so there is no need to worry about the order of Set and Add, of course, the second parameter is a pointer object of a Cookie. After setting the cookie, the next step is to read the cookie.

Reading Cookie

There are many ways to read cookies, cookies are encapsulated in the header, of course, they can be processed through the header method.

func getCookieHandler(w http.ResponseWriter, r *http.Request) {
    h := r.Header["Cookie"]
    fmt.Fprintln(w, h)
}

Without using the Header method, you can also use the Request method:

func getCookieHandler(w http.ResponseWriter, r *http.Request) {
    c1, err := r.Cookie("first_cookie")
    if err != nil{
        fmt.Fprintln(w, "Cannot get cookie")
    }
    cs := r.Cookies()
    fmt.Fprintln(w, c1)
    fmt.Fprintln(w, cs)
}

When accessing, it can be found that r.Cookie returns the key-value pair for the key, and r.Cookies returns the key-value pairs of all cookies.

Cookie and Message

Cookies have many functions, usually recording some information of the client, used for user login verification. Now we need to use cookies to implement a small feature---Messages. Usually, after a web request is made, the response returns data, and some messages can also be set to guide the user.

func setMessageHandler(w http.ResponseWriter, r *http.Request) {
    msg := []byte("Hello World")
    c := http.Cookie{
        Name: "flash",
        Value:base64.URLEncoding.EncodeToString(msg),
    }
    http.SetCookie(w, &c)
}
func getMessageHandler(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("flash")
    if err != nil {
        if err == http.ErrNoCookie {
            fmt.Fprintln(w, "No message found")
        }
    } else {}}
        rc := http.Cookie{
            Name: "flash",
            MaxAge: -1,
            Expires:time.Unix(1, 0),
        }
        http.SetCookie(w, &rc)
        val, _ := base64.URLEncoding.DecodeString(c.Value)
        fmt.Fprintln(w, string(val))
    }
}

The setMessageHandler function is very simple, just create a cookie instance, write the message into the cookie, and then return it to the client.

The getMessageHandler will first read the cookie with the key 'flash'. If the content is not read, it means that the message does not exist. Otherwise, another cookie will be created, and its expiration time will be set here to clear the cookie. Then, the read-out message will be returned to the client to complete the message communication.

Summary

We discussed the basic application of cookies in Go. In current web development, people are paying more and more attention to network security, so the security of cookies has also become a concern for users. The original cookie encapsulation in Go is relatively simple. However, the Go community has developed many wheels to implement secure cookies, such as gorilla/The securecookie library. In actual development, it may be necessary to use some third-party libraries or packages to complete the function.

I hope the content described in this article will be helpful to everyone in Go language program design.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like