locstor

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2018 License: MIT Imports: 6 Imported by: 1

README

Humble/locstor

GoDoc

Version 0.2.2

locstor provides gopherjs bindings for the localStorage API. It allows you to store and retrieve any arbitrary go data structure, and is intended to be compiled to javascript with gopherjs and run in the browser. locstor works great as a stand-alone package or in combination with other Humble packages.

locstor is written in pure go. It feels like go, follows go idioms when possible, and compiles with the go tools.

Browser Support

locstor works with IE9+ (with a polyfill for typed arrays) and all other modern browsers. locstor compiles to javascript via gopherjs and this is a gopherjs limitation.

Installation

Install locstor like you would any other go package:

go get github.com/go-humble/locstor

You will also need to install gopherjs if you don't already have it. The latest version is recommended. Install gopherjs with:

go get -u github.com/gopherjs/gopherjs

You can compile your application to javascript using the gopherjs build command. Run gopherjs --help to learn more about the gopherjs command-line tool.

Example Usage

Accessing the localStorage API Directly

Use SetItem to store an item in localStorage:

if err := locstor.SetItem('foo', 'bar'); err != nil {
	// Handle err
}

Use GetItem to get an item from localStorage:

item, err := locstor.GetItem('foo')
if err != nil {
	// Handle err
}
fmt.Println(item)
// Output:
//   bar

Use Key to get the key for a specific item:

key, err := locstor.Key('bar')
if err != nil {
	// Handle err
}
fmt.Println(key)
// Output:
//   foo

Use RemoveItem to remove an existing item from localStorage:

if err := locstor.RemoveItem('foo'); err != nil {
	// Handle err
}
_, err := locstor.GetItem('foo')
fmt.Println(err)
// Output:
//   Could not find an item with the given key: foo

Use Length to get the number of items currently in localStorage:

count, err := locstor.Length()
if err != nil {
	// Handle err
}

Use Clear to remove all items from localStorage:

if err := locstor.Clear(); err != nil {
	// Handle err
}
Using a DataStore

You can also use a DataStore, which is an abstraction layer built on top of localStorage capable of storing and retrieving arbitrary go data structures, not just strings.

Use NewDataStore to create a new DataStore. It accepts an EncoderDecoder as an argument. There are two encodings provided out-of-the-box: JSONEncoding and BinaryEncoding. You should choose JSONEncoding if you want the data stored in localStorage to be more readable and BinaryEncoding if you want the data to take up less space. You can also provide a custom encoding by implementing the EncoderDecoder interface.

store := locstor.NewDataStore(JSONEncoding)

Use Save to save data structures in localStorage:

if err := store.Save("numbers", []int{1, 2, 3}); err != nil {
	// Handle err
}

Use Find to get existing data structures out of localStorage. Find works similarly to json.Unmarshal from the standard library. The second argument to Find, called holder, is a pointer to a variable that is capable of holding the decoded data structure. Since in this case we stored a slice of ints, the type of holder should be *[]int.

gotNumbers := []int{}
if err := store.Find("numbers", &gotNumbers); err != nil {
	// Handle err
}
fmt.Println(gotNumbers)
// Output:
//   [1 2 3]

Use Delete to delete an existing data structure from localStorage:

if err := store.Delete("numbers"); err != nil {
	// Handle err
}
gotNumbers := []int{}
_, err := locstor.Find('numbers', &gotNumbers)
fmt.Println(err)
// Output:
//   Could not find an item with the given key: numbers
Handling Errors

ErrLocalStorageNotSupported will be returned by any function or method if localStorage is not supported in the current browser. ErrLocalStorageNotSupported is just a variable, so you can do direct comparisons:

if err := locstor.GetItem("foo"); err != nil {
	if err == locstor.ErrLocalStorageNotSupported {
		// Handle an ErrLocalStorageNotSupported error 
	} else {
		// Handle some other type of error
	}
}

Testing

locstor uses the karma test runner to test the code running in actual browsers.

The tests require the following additional dependencies:

Don't forget to also install the karma command line tools with npm install -g karma-cli.

You will also need to install a launcher for each browser you want to test with, as well as the browsers themselves. Typically you install a karma launcher with npm install -g karma-chrome-launcher. You can edit the config file at karma/test-mac.conf.js or create a new one (e.g. karma/test-windows.conf.js) if you want to change the browsers that are tested on.

Once you have installed all the dependencies, start karma with karma start karma/test-mac.conf.js (or your customized config file, if applicable). Once karma is running, you can keep it running in between tests.

Next you need to compile the test.go file to javascript so it can run in the browsers:

gopherjs build karma/go/locstor_test.go -o karma/js/locstor_test.js

Finally run the tests with karma run karma/test-mac.conf.js (changing the name of the config file if needed).

If you are on a unix-like operating system, you can recompile and run the tests in one go by running the provided bash script: ./karma/test.sh.

Contributing

See CONTRIBUTING.md

License

locstor is licensed under the MIT License. See the LICENSE file for more information.

Documentation

Overview

Package locstor provides gopherjs bindings for the localStorage API. It allows you to store and retrieve any arbitrary go data structure, and is intended to be compiled to javascript with gopherjs and run in the browser.

Version 0.2.2

For the full source code, example usage, and more information visit https://github.com/go-humble/locstor.

Index

Constants

This section is empty.

Variables

View Source
var (
	// BinaryEncoding is a ready-to-use implementation of EncoderDecoder which
	// encodes data structures in a binary format using the gob package.
	BinaryEncoding = &binaryEncoderDecoder{}
	// JSONEncoding is a ready-to-use implementation of EncoderDecoder which
	// encodes data structures as json.
	JSONEncoding = &jsonEncoderDecoder{}
)
View Source
var ErrLocalStorageNotSupported = errors.New("localStorage does not appear to be supported/enabled in this browser")

ErrLocalStorageNotSupported is returned if localStorage is not supported.

Functions

func Clear

func Clear() (err error)

Clear removes all items from localStorage.

func DetectStorage added in v0.2.0

func DetectStorage() (ok bool)

DetectStorage detects and (re)initializes the localStorage.

func GetItem

func GetItem(key string) (s string, found bool, err error)

GetItem finds and returns the item identified by key.

func Key

func Key(item string) (s string, found bool, err error)

Key finds and returns the key associated with the given item.

func Length

func Length() (l int, err error)

Length returns the number of items currently in localStorage.

func RemoveItem

func RemoveItem(key string) (err error)

RemoveItem removes the item with the given key from localStorage.

func SetItem

func SetItem(key, item string) (err error)

SetItem saves the given item in localStorage under the given key.

Types

type DataStore

type DataStore struct {
	Encoding EncoderDecoder
}

DataStore is an object with methods for storing and retrieving arbitrary go data structures in localStorage.

func NewDataStore

func NewDataStore(encoding EncoderDecoder) *DataStore

NewDataStore creates and returns a new DataStore with the given encoding. locstor.JSON and locstor.Binary are two encodings provided by default. You can also pass in a custom encoding.

func (DataStore) Delete

func (store DataStore) Delete(key string) error

Delete deletes the item with the given key from localStorage.

func (DataStore) Find

func (store DataStore) Find(key string, holder interface{}) (bool, error)

Find finds the item with the given key in localStorage and scans it into holder. holder must be a pointer to some data structure which is capable of holding the item. In general holder should be the same type as the item that was passed to Save.

func (DataStore) Save

func (store DataStore) Save(key string, item interface{}) error

Save saves the given item under the given key in localStorage.

type Decoder

type Decoder interface {
	Decode([]byte, interface{}) error
}

Decoder is an interface implemented by objects which can decode a slice of bytes into an arbitrary go object.

type Encoder

type Encoder interface {
	Encode(interface{}) ([]byte, error)
}

Encoder is an interface implemented by objects which can encode an arbitrary go object into a slice of bytes.

type EncoderDecoder

type EncoderDecoder interface {
	Encoder
	Decoder
}

EncoderDecoder is an interface implemented by objects which can both encode an arbitrary go object into a slice of bytes and decode that slice of bytes into an arbitrary go object. EncoderDecoders should have the property that Encode(Decode(x)) == x for all objects x which are encodable.

Jump to

Keyboard shortcuts

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