Categorygithub.com/mitchellh/pointerstructure
modulepackage
1.2.1
Repository: https://github.com/mitchellh/pointerstructure.git
Documentation: pkg.go.dev

# README

pointerstructure GoDoc

pointerstructure is a Go library for identifying a specific value within any Go structure using a string syntax.

pointerstructure is based on JSON Pointer (RFC 6901), but reimplemented for Go.

The goal of pointerstructure is to provide a single, well-known format for addressing a specific value. This can be useful for user provided input on structures, diffs of structures, etc.

Features

  • Get the value for an address

  • Set the value for an address within an existing structure

  • Delete the value at an address

  • Sorting a list of addresses

Installation

Standard go get:

$ go get github.com/mitchellh/pointerstructure

Usage & Example

For usage and examples see the Godoc.

A quick code example is shown below:

complex := map[string]interface{}{
	"alice": 42,
	"bob": []interface{}{
		map[string]interface{}{
			"name": "Bob",
		},
	},
}

value, err := pointerstructure.Get(complex, "/bob/0/name")
if err != nil {
	panic(err)
}

fmt.Printf("%s", value)
// Output:
// Bob

Continuing the example above, you can also set values:

value, err = pointerstructure.Set(complex, "/bob/0/name", "Alice")
if err != nil {
	panic(err)
}

value, err = pointerstructure.Get(complex, "/bob/0/name")
if err != nil {
	panic(err)
}

fmt.Printf("%s", value)
// Output:
// Alice

The library also supports Get operations on structs including using the pointer struct tag to override struct field names:

	input := struct {
		Values map[string]interface{} `pointer:"embedded"`
	}{
		Values: map[string]interface{}{
			"alice": 42,
			"bob": []interface{}{
				map[string]interface{}{
					"name": "Bob",
				},
			},
		},
	}

	value, err := Get(input, "/embedded/bob/0/name")
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s", value)
// Output:
// Bob

# Functions

Get reads the value at the given pointer.
MustParse is like Parse but panics if the input cannot be parsed.
Parse parses a pointer from the input string.
Set sets the value at the given pointer.
Sort does an in-place sort of the pointers so that they are in order of least specific to most specific alphabetized.

# Variables

ErrConvert is returned if an item is not of a requested type.
ErrInvalidKind is returned if the item is not a map, slice, array, or struct.
ErrNotFound is returned if a key in a query can't be found.
ErrOutOfRange is returned if a query is referencing a slice or array and the requested index is not in the range [0,len(item)).
ErrParse is returned if the query cannot be parsed.

# Structs

No description provided by the author
Pointer represents a pointer to a specific value.

# Type aliases

PointerSlice is a slice of pointers that adheres to sort.Interface.
ValueTransformationHookFn transforms a Go data structure into another.