jsonfile

package module
v0.0.0-...-699d1da 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: 1

README

jsonfile:

Use jsonfile to persist a Go value to a JSON file.

type JSONFile
    func Load[Data any](path string) (*JSONFile[Data], error)
    func New[Data any](path string) (*JSONFile[Data], error)
    func (p *JSONFile[Data]) Read(fn func(data *Data))
    func (p *JSONFile[Data]) Write(fn func(*Data) error) error

There is a bit more thought put into the few lines of code in this repository than you might expect. If you want more details, see the blog post.

Documentation

Overview

Package jsonfile 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 JSONFile

type JSONFile[Data any] struct {
	// contains filtered or unexported fields
}

JSONFile holds a Go value of type Data and persists it to a JSON file. Data is accessed and modified using the Read and Write methods. Create a JSONFile using the New or Load functions.

func Load

func Load[Data any](path string) (*JSONFile[Data], error)

Load loads an existing JSONFileData 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 file or create it (which you may want to do in a development environment), combine Load with New, like this:

db, err := jsonfile.Load[Data](path)
if os.IsNotExist(err) {
	db, err = jsonfile.New[Data](path)
}

func New

func New[Data any](path string) (*JSONFile[Data], error)

New creates a new empty JSONFile at the given path.

func (*JSONFile[Data]) Read

func (p *JSONFile[Data]) Read(fn func(data *Data))

Read calls fn with the current copy of the data.

func (*JSONFile[Data]) Write

func (p *JSONFile[Data]) Write(fn func(*Data) error) error

Write calls fn with a copy of the data, 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