Git Product home page Git Product logo

locstor's Introduction

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.

locstor's People

Contributors

albrow avatar dave avatar mckael avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.