Setting HTTP Cookie in Golang [SOLVED]

Setting HTTP Cookie in Golang [SOLVED]

In previous chapter, we discussed http server and client in Golang. Today, we will walk through how to manage http cookie in Go with net/http package.

http cookie: HTTP cookies (also called web cookies, Internet cookies, browser cookies, or simply cookies) are small blocks of data created by a web server while a user is browsing a website and placed on the user’s computer or other device by the user’s web browser. Cookies are placed on the device used to access a website, and more than one cookie may be placed on a user’s device during a session.

**net/http package:**Package http provides HTTP client and server implementations. Get, Head, Post, and PostForm make HTTP (or HTTPS) requests.


Create simple http server

We have written a detailed article on setting up web server using golang. Here is an example of http server which print out “Hello, world!” for every GET request:

package main

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "Hello, world!\n")
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":8080", nil)
}

Output:

Now you can access to http://localhost:8080/

image


Set cookies in HTTP web server

cookie in Golang is defined as a struct:

type Cookie struct {
    Name  string
    Value string

    Path       string    // optional
    Domain     string    // optional
    Expires    time.Time // optional
    RawExpires string    // for reading cookies only

    // MaxAge=0 means no 'Max-Age' attribute specified.
    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
    // MaxAge>0 means Max-Age attribute present and given in seconds
    MaxAge   int
    Secure   bool
    HttpOnly bool
    SameSite SameSite
    Raw      string
    Unparsed []string // Raw text of unparsed attribute-value pairs
}

For the usage of all fields, you can refer to documentation page.

In this case, we can use SetCookie() function in net/http package to set a http cookie.

func SetCookie(w ResponseWriter, cookie *Cookie): SetCookie adds a Set-Cookie header to the provided ResponseWriter’s headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.

Here’s an example of using SetCookie``() function to set cookies:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func helloHandler(w http.ResponseWriter, req *http.Request) {
    // set cookie for storing token
    cookie := http.Cookie{}
    cookie.Name = "accessToken"
    cookie.Value = "ro8BS6Hiivgzy8Xuu09JDjlNLnSLldY5"
    cookie.Expires = time.Now().Add(365 * 24 * time.Hour)
    cookie.Secure = false
    cookie.HttpOnly = true
    cookie.Path = "/"
    http.SetCookie(w, &cookie)

    fmt.Fprintf(w, "This is cookies!\n")
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.ListenAndServe(":8080", nil)
}

Output:


Fetch cookies in HTTP web server

Now let’s see how to get a cookie that has been set:

    cookie, _ := r.Cookie(<span class="hljs-string">"page"</span>)
    fmt.Fprint(w, cookie)

Here is another way to get a cookie:

    for _, cookie := range r.Cookies() {
        fmt.Fprint(w, cookie.Name)
    }

Here is full version of fetch cookies in Go:

package main

import (
    "fmt"
    "net/http"
    "time"
)

func helloHandler(w http.ResponseWriter, req *http.Request) {
    // set cookie for storing token
    cookie := http.Cookie{}
    cookie.Name = "accessToken"
    cookie.Value = "ro8BS6Hiivgzy8Xuu09JDjlNLnSLldY5"
    cookie.Expires = time.Now().Add(365 * 24 * time.Hour)
    cookie.Secure = false
    cookie.HttpOnly = true
    cookie.Path = "/"
    http.SetCookie(w, &cookie)

    cookie2 := http.Cookie{}
    cookie2.Name = "page"
    cookie2.Value = "GoLinuxCloud"
    cookie2.Expires = time.Now().Add(365 * 24 * time.Hour)
    cookie2.Secure = false
    cookie2.HttpOnly = true
    cookie2.Path = "/"
    http.SetCookie(w, &cookie2)

    fmt.Fprintf(w, "This is cookies!\n")
}

func printCookie(w http.ResponseWriter, req *http.Request) {
    var returnStr string
    for _, cookie := range req.Cookies() {
        returnStr = returnStr + cookie.Name + ":" + cookie.Value + "\n"
    }
    fmt.Fprintf(w, returnStr)
}

func main() {
    http.HandleFunc("/", helloHandler)
    http.HandleFunc("/print", printCookie)
    http.ListenAndServe(":8080", nil)
}

Output:


Summary

In this example, we have discussed about http cookies in Golang. All client data is saved in cookies on the client side. Cookies have various security issues, as you may have seen. For instance, bad third party websites may be able to crack usernames and passwords and acquire the information.


References

https://en.wikipedia.org/wiki/HTTP_cookie
https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol

Tuan Nguyen

Tuan Nguyen

Data Scientist

Proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise spanning these technologies, he develops robust solutions and implements efficient data processing and management strategies across various projects and platforms.