Our application is beginning to get a little more real now; in the previous chapter, we added some APIs and client-side interfaces to them.
In our application's current state, we've added /api/comments
, /api/comments/[id]
, /api/pages
, and /api/pages/[id]
, thus making it possible for us to get and update our data in JSON format and making the application better suited for Ajax and client-side access.
Though we can now add comments and edit them directly through our API, there is absolutely no restriction on who can perform these actions. In this chapter, we'll look at the ways to limit access to certain assets, establishing identities, and securely authenticating when we have them.
By the end, we should be able to enable users to register and log in and utilize sessions, cookies, and flash messages to keep user state in our application in a secure way.
The most common, fundamental, and simplest way to create persistent memory across a user's session is by utilizing cookies.
Cookies provide a way to share state information across requests, URL endpoints, and even domains, and they have been used (and abused) in every possible way.
Most often, they're used to keep a track of identity. When a user logs into a service, successive requests can access some aspects of the previous request (without duplicating a lookup or the login module) by utilizing the session information stored in a cookie.
If you're familiar with cookies in any other language's implementation, the basic struct
will look familiar. Even so, the following relevant attributes are fairly lockstep with the way a cookie is presented to the client:
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 }
That's a lot of attributes for a very basic struct
, so let's focus on the important ones.
The Name
attribute is simply a key for the cookie. The Value
attribute represents its contents and Expires
is a Time
value for the moment when the cookie should be flushed by a browser or another headless recipient. This is all you need in order to set a valid cookie that lasts in Go.
Beyond the basics, you may find setting a Path
, Domain
, and HttpOnly
useful, if you want to lock down the accessibility of the cookie.