Site icon Golang Libraries, Apps, Golang Jobs and Go Tutorials

How to work with Cookies in Golang

how to work with cookies

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:

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
}

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:

Exit mobile version