zhash

package module
v0.0.0-...-2b0d504 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2022 License: MIT Imports: 7 Imported by: 2

README

zhash

Bored of type switches when dealing with huge nested maps? zhash is for you!

Create one

import zhash

func main() {
    hash := zhash.NewHash()
}

Then fill it from toml:

    func tomlUnmarshal(b []byte, v interface{}) error {
	    _, err := toml.Decode(string(b), v)
	    return err
    }

    hash.SetUnmarshaller(tomlUnmarshal)
    hash.ReadHash(reader)

or initialize from existing map[string]interface{}:

    hash := zhash.HashFromMap(yourFancyMap)

And use it through different getters and setters:

    s, _ := hash.GetString("path", "to", "nested", "item")

    hash.Set("Some new var", "path", "to", "existing", "or", "new", "element")

All the things is in dev branch still.

Documentation

Overview

Package zhash gives you the tool to operate huge map[string]interface{} with pleasure.

Creating Hash

There are two methods to create new Hash. First, you can create Hash from existing map[string]interface{} using HashFromMap(m) function:

m := map[string]interface{}{
	"field": "value",
	"Id": 10,
}

h := zhash.HashFromMap(m)

Or you can create an empty hash by NewHash() function. Then you can fill it via Set, or you can set any function fiting the Unmarshaller type, and read your hash from any reader (file or bytes.Buffer, for example).

h := zhash.NewHash()
h.SetUnmarshallerFunc(json.Unmarshal)

h.ReadHash(fd)

Accessing data

So, you have your hash. How can you access it's data? It's simple --- use Get<Type> for getting single items, Get<Type>Slice for getting slices, Set for changing items, Delete for deleting childs of nested (or not) maps, and Append<Type>Slice for appending slices.

Setting data

Set make no difference on what was there before setting new value. So, you can easily replace any map with int, and loose all underlying data. Also Set creates all needed parents if needed, and replaces any found element in the way by map[string]interface{}. So be double careful with Set.

Appending slices

Append<Type>Slice will succeed if Get<Type>Slice return no err, or err is not found error. Append<Type>Slice replaces original slice, so, for example, if original slice "some.slice" was []interface{} containing only ints, and you do AppendIntSlice, after append "some.slice" would become []int64.

Example (HashFromMap)

Example HashFromMap shows how to initialize your hash from map

package main

import (
	"fmt"
	"log"

	"github.com/zazab/zhash"
)

func main() {
	m := map[string]interface{}{
		"plainValue": 10.1,
		"subMap": map[string]interface{}{
			"elem1": 10,
			"elem2": true,
		},
	}

	h := zhash.HashFromMap(m)

	f, err := h.GetFloat("plainValue")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(f)
}
Output:

10.1
Example (ReadHash)

Example ReadHash shows how to initialize your hash using Unmarshal function You can use any function that satisfies Unmarshaller type for ReadHash. For example, see TomlExample for example of using BurntSushi/toml for unmarshalling

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"

	"github.com/zazab/zhash"
)

func main() {
	h := zhash.NewHash()
	h.SetMarshallerFunc(json.Marshal)
	h.SetUnmarshallerFunc(json.Unmarshal)

	b := bytes.NewBuffer([]byte("{\"this\": \"is\", \"some_json_map\": 14.1}"))

	err := h.ReadHash(b)
	if err != nil {
		log.Fatal(err)
	}

	s, err := h.GetString("this")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("This %s working", s)
}
Output:

This is working
Example (TomlUnmarshaller)
package main

import (
	"bytes"
	"fmt"

	"github.com/BurntSushi/toml"
	"github.com/zazab/zhash"
)

func unmarshalToml(d []byte, t interface{}) error {
	_, err := toml.Decode(string(d), t)
	return err
}

func main() {
	h := zhash.NewHash()
	h.SetUnmarshallerFunc(unmarshalToml)

	blob := []byte(`
key1 = "string"
key2 = 10
`)

	b := bytes.NewBuffer(blob)
	h.ReadHash(b)
	fmt.Println(h.String())

}
Output:

{
  "key1": "string",
  "key2": 10
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsNotFound

func IsNotFound(err error) bool

Check if given err represents zhash "Not Found" error. Great for checking if asked value is zero or just not set.

Types

type Hash

type Hash struct {
	// contains filtered or unexported fields
}

func HashFromMap

func HashFromMap(ma map[string]interface{}) Hash

Loads existing map[string]interface{} to Hash. Marshaller and Unmarshallers are optional, if you don't need it pass nil to them. You can set (or change) them later using Hash.SetMarshaller and Hash.SetUnmarshaller.

func NewHash

func NewHash() Hash

func NewHashPtr

func NewHashPtr() *Hash

func (Hash) AppendFloatSlice

func (h Hash) AppendFloatSlice(val float64, path ...string) error

func (Hash) AppendIntSlice

func (h Hash) AppendIntSlice(val int64, path ...string) error

func (Hash) AppendMapSlice

func (hash Hash) AppendMapSlice(val map[string]interface{}, path ...string) error

func (Hash) AppendSlice

func (h Hash) AppendSlice(val interface{}, path ...string) error

func (Hash) AppendStringSlice

func (h Hash) AppendStringSlice(val string, path ...string) error

func (Hash) Delete

func (h Hash) Delete(path ...string) error

func (Hash) Get

func (h Hash) Get(path ...string) interface{}

Retrieves value from hash returns nil if nothing found

func (Hash) GetBool

func (h Hash) GetBool(path ...string) (bool, error)

func (Hash) GetFloat

func (h Hash) GetFloat(path ...string) (float64, error)

func (Hash) GetFloatSlice

func (h Hash) GetFloatSlice(path ...string) ([]float64, error)

func (Hash) GetHash

func (h Hash) GetHash(path ...string) (Hash, error)

Retrieves map[string]interface{} and converts it to Hash. Returns error if can not convert target value, or value doesn'n found. If not found returns emty map[string]interface{} not nil

func (Hash) GetInt

func (h Hash) GetInt(path ...string) (int64, error)

func (Hash) GetIntSlice

func (h Hash) GetIntSlice(path ...string) ([]int64, error)

Returns []int64 if any of []int, []int64 or []interface{} is found under the path. If target is []interface{} it will fails to convert if type of any element is not int or int64.

func (Hash) GetMap

func (h Hash) GetMap(path ...string) (map[string]interface{}, error)

Retrieves map[string]interface{} returns error if any can not convert target value, or value doesn't found. If not found, returns empty Hash, not nil

func (Hash) GetMapSlice

func (hash Hash) GetMapSlice(path ...string) ([]map[string]interface{}, error)

func (Hash) GetRoot

func (h Hash) GetRoot() map[string]interface{}

Returns root map[string]interface{}

func (Hash) GetSlice

func (h Hash) GetSlice(path ...string) ([]interface{}, error)

Retrieves []interface{} from hash. Will fail if target slice have different type ([]int for example).

func (Hash) GetString

func (h Hash) GetString(path ...string) (string, error)

func (Hash) GetStringSlice

func (h Hash) GetStringSlice(path ...string) ([]string, error)

func (Hash) Keys

func (h Hash) Keys() []string

Returns root keys of Hash

func (Hash) Len

func (h Hash) Len() int

Returns len of root map

func (Hash) MarshalJSON

func (h Hash) MarshalJSON() ([]byte, error)

func (*Hash) ReadHash

func (h *Hash) ReadHash(r io.Reader) error

Unmarshall hash from given io.Reader using function setted via zhash.Hash.SetUnmarshaller

func (Hash) Reader

func (h Hash) Reader() (io.Reader, error)

func (Hash) Set

func (h Hash) Set(value interface{}, path ...string)

func (*Hash) SetMarshallerFunc

func (h *Hash) SetMarshallerFunc(fu Marshaller)

Sets function for marshalling via Hash.WriteHash(fd)

func (*Hash) SetRoot

func (h *Hash) SetRoot(value map[string]interface{})

func (*Hash) SetUnmarshallerFunc

func (h *Hash) SetUnmarshallerFunc(fu Unmarshaller)

Set function for unmarshalling via Hash.ReadHash

func (Hash) String

func (h Hash) String() string

Returns indented json with your map

func (Hash) WriteHash

func (h Hash) WriteHash(w io.Writer) error

Mashall hash using supplied Marshaller function and writes it to w

type Marshaller

type Marshaller func(interface{}) ([]byte, error)

type Unmarshaller

type Unmarshaller func([]byte, interface{}) error

Jump to

Keyboard shortcuts

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