Persistent Storage with gob
This lesson explains how to build persistent storage for the application.
We'll cover the following...
When the goto
process (the web-server on a port) ends, and this has to happen sooner or later, the map with the shortened URLs in memory will be lost. To preserve our map data, we need to save them to a disk file. We will modify URLStore
so that it writes its data to a file, and restores that data on goto
start-up. For this, we will use Go’s encoding/gob
package, which is a serialization and deserialization package that turns data structures into arrays (or more accurately slices) of bytes and vice versa (see Chapter 3).
With the gob
package’s NewEncoder
and NewDecoder
functions, you can decide where you write the data to or read it from. The resulting Encoder
and Decoder
objects provide Encode
and Decode
methods for writing and reading Go data structures to and from files. Encoder
also implements the Writer
interface, and so does Decoder
for the Reader
interface.
We will add a new file field (of type *os.File
) to URLStore
that will be a handle to an open file that can be used for writing and reading.