unpack

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

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

Go to latest
Published: Mar 9, 2023 License: MIT Imports: 3 Imported by: 0

README

Go Reference

unpack

unpack provides a convenient mechanism to read a JSON config file comprising an single object with attributes representing unique values of the same structure:

{
	"countries": {
		"United Kingdom": { 
			"capital": "London",
			"population": {
				"2023": 66000000
			}
		},
		"United States": {
			"capital": "Washington",
			"population": {
				"2023": 314000000
			}
		}
	}
}

Use

Two struct types are required:

  • A receiving struct that includes the attributes and associated json tags necessary to parse the data successfully - i.e. as required to use json.Unmarshal. In addition, this struct must have a pointer type implementation of SetName so that the struct implements the interface Unpackable.
  • A factory struct that can manufacture pointer instances of the receiving struct
type Country struct {
	Name string
	Capital string `json:"capital"`
	Population map[string]int `json:"population"`
}

func (c *Country) SetName(name string) {
	c.Name = name
}

type CountryFact struct{}

func (f CountryFact) New() Unpackable {
	return new(Country)
}

func UnmarshalCountries(b []byte)  []*Country {
	items, _ := Unpack(b, CountryFact{})
	countries := make([]*Country, len(items))
	for i, item := range items {
		countries[i] = item.(*Country)
	}
	return countries
}

How?

The command line is all you need.

go get github.com/gford1000-go/unpack

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Unpackable

type Unpackable interface {
	SetName(name string)
}

Unpackable instances provide the ability to assign their name using the attribute name of the enclosing JSON object

func Unpack

func Unpack[F UnpackableFactory](b []byte, fact F) ([]Unpackable, error)

Unpack returns the slice of Unpackable instances within a JSON objects The Unpackable must be a pointer type implementation of the interface.

func UnpackAndValidate

func UnpackAndValidate(b []byte, fact UnpackableFactory) ([]Unpackable, error)

UnpackAndValidate returns a validated set of Unpackables, where the validation to be performed is defined in the tag of each attribute see: https://pkg.go.dev/github.com/asaskevich/govalidator?utm_source=godoc

type UnpackableFactory

type UnpackableFactory interface {
	New() Unpackable
}

UnpackableFactory creates instances of Unpackable

Jump to

Keyboard shortcuts

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