jsonfiledb

package module
v0.0.0-...-7783171 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2024 License: BSD-3-Clause Imports: 6 Imported by: 0

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL