Documentation
¶
Overview ¶
Package jsonfiledb persists a Go value to a JSON file.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type JSONFileDB ¶
type JSONFileDB[DB any] struct { // contains filtered or unexported fields }
JSONFileDB holds a Go value of type DB and persists it to a JSON file. Data is accessed and modified using the Read and Write methods. Create a JSONFileDB using the New or Load functions.
func Load ¶
func Load[DB any](path string) (*JSONFileDB[DB], error)
Load loads an existing JSONFileDB from the given path.
If the file does not exist, Load returns an error that can be checked with os.IsNotExist.
Load and New are separate to avoid creating a new file when starting a service, which could lead to data loss. To both load an existing DB or create it (which you may want to do in a development environment), combine Load with New, like this:
db, err := Load[DB](path) if os.IsNotExist(err) { db, err = New[DB](path) }
func New ¶
func New[DB any](path string) (*JSONFileDB[DB], error)
New creates a new empty JSONFileDB at the given path.
func (*JSONFileDB[DB]) Read ¶
func (p *JSONFileDB[DB]) Read(fn func(db *DB))
Read calls fn with the current copy of the DB.
func (*JSONFileDB[DB]) Write ¶
func (p *JSONFileDB[DB]) Write(fn func(db *DB) error) error
Write calls fn with a copy of the DB, then writes the changes to the file. If fn returns an error, Write does not change the file and returns the error.