In this post from Alex Edwards, he going to run through how to use cookies in your Golang web application to persist data between HTTP requests for a specific client. We’ll start simple and slowly build up a working application that covers the following topics:
- Basic reading and writing of cookies
- Encoding special characters and maximum length
- Using tamper-proof (signed) cookies
- Using confidential (encrypted) and tamper-proof cookies
- Storing custom data types in cookies
Hint: If you’re new to web development and need a general introduction to what cookies are and how they work, I recommend reading this MDN article before continuing.
If you just want the final code, rather than the explanations, you can find it in this gist.
Basic usage of Cookies with Golang
The first thing to know is that cookies in Go are represented by the http.Cookie type. This is a struct that looks like this:
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
// 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
}
Name
is the cookie name. It can contain any US-ASCII characters except( ) < > @ , ; : \ " / [ ? ] = { }
and space, tab and control characters. It is a mandatory field.Value
contains the data that you want to persist. It can contain any US-ASCII characters except, ; \ "
and space, tab and control characters. It is a mandatory field.Path
,Domain
,Expires
,MaxAge
,Secure
,HttpOnly
andSameSite
map directly to the respective cookie attributes. All of these are optional fields.- If set, the value of the
SameSite
field should be one of the SameSite constants from thenet/http
package. - The
RawExpires
,Raw
andUnparsed
fields are only used when your Go program is acting as a client (rather than a server) and parsing the cookies from a HTTP response. Most of the time you won’t need to use these fields.
Cookies can be written in a HTTP response using the http.SetCookie()
function, and read from a HTTP request using the *Request.Cookie()
method.
Let’s jump in and use these things in a working example.
If you’d like to follow along, please run the following commands to set up a basic project scaffold:
There is no ads to display, Please add some