The session store

Unlike the product records, which are stored in the Redis database, the items a user chooses to place in their shopping cart is transitory, and it's customized for individual use. This being the case, it makes much more sense to store the state of the shopping cart in a session, rather than in the database.

We will use the Gorilla sessions package to create sessions and store data to the sessions. We will utilize the session.NewFileSystemStore type to save the session data to the server's file system.

First, we will add a new field (shown in bold) to the common.Env struct (defined in the common/common.go source file), which will hold the FileSystemStore instance so that it is accessible throughout the server-side web application:

type Env struct {
DB datastore.Datastore
TemplateSet *isokit.TemplateSet
Store *sessions.FilesystemStore
}

Inside the main function defined in the igweb.go source file, we will make a call to the initializeSessionstore function and pass in the env object:

initializeSessionstore(&env)

The initializeSessionstore function is responsible for creating the session store on the server side:

func initializeSessionstore(env *common.Env) {
if _, err := os.Stat("/tmp/igweb-sessions"); os.IsNotExist(err) {
os.Mkdir("/tmp/igweb-sessions", 711)
}
env.Store = sessions.NewFilesystemStore("/tmp/igweb-sessions", []byte(os.Getenv("IGWEB_HASH_KEY")))
}

In the if conditional, we first check to see whether the designated path where the session data will be stored, /tmp/igweb-sessions, exists. If the path does not exist, we create the folder by calling the Mkdir function from the os package.

We will initialize a new file system session store by calling the NewFileSystemStore function in the sessions package, passing in the path where sessions will be saved and the authentication key for the session. We will populate the Store property of the env object with the newly created FileSystemStore instance.

Now that we have the session store in place, let's implement the server-side ShoppingCartHandler function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.62