struct2

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2022 License: MIT Imports: 4 Imported by: 8

README

struct2

This repository helps to work with struct, convert map and get information about that.

This is a modified version of common struct to map libraries with cool features.

Supported tags: -, omitempty, string, ptr2, omitnested, flatten.

Convertion order is -, omitempty, string, ptr2, custom hook function, hooker interface, omitnested + flatten

Usage

go get github.com/worldline-go/struct2

Get decoder and run Map method.

type ColorGroup struct {
    ID     int      `db:"id"`
    Name   string   `db:"name"`
    Colors []string `db:"colors"`
    // custom type with implemented Hooker interface
    // covertion result to time.Time
    Date types.Time `db:"time"`
    // unkown type but to untouch it add omitnested to keep that struct type
    RGB *null.String `db:rgb,omitempty,omitnested`
}

decoder := struct2.Decoder{
    TagName: "db",
}

// get map[string]interface{}
result := decoder.Map(group)

Custom decoder can be use in struct witch have struct2.Hooker interface.
Or set a slice of custom struct2.HookFunc functions in decoder.

Check documentation examples.

Tags Information

omitnested: very helpful to don't want to touch data.

ptr2: convert pointer to the concrete value, if pointer is nil new value generating. ptr2 to effect custom hook functions and hooker interface also omitnested.


Inspired Projects

fatih/structs
mitchellh/mapstructure

Documentation

Overview

Example
package main

import (
	"fmt"
	"sort"
	"time"

	"github.com/worldline-go/struct2"
	"github.com/worldline-go/struct2/types"
)

func SortPrint(m map[string]interface{}) {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for _, k := range keys {
		fmt.Printf("Type: %T, Value: %v\n", m[k], m[k])
	}
}

func main() {
	type ColorGroup struct {
		ID     int        `struct:"id"`
		Name   string     `struct:"name"`
		Colors []string   `struct:"colors"`
		Date   types.Time `struct:"time"`
	}

	d, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")

	group := ColorGroup{
		ID:     1,
		Name:   "Reds",
		Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
		Date:   types.Time{Time: d},
	}

	decoder := struct2.Decoder{}

	result := decoder.Map(group)

	// fmt.Printf("%#v", result)
	SortPrint(result)
}
Output:

Type: []string, Value: [Crimson Red Ruby Maroon]
Type: int, Value: 1
Type: string, Value: Reds
Type: time.Time, Value: 2006-01-02 15:04:05 +0000 UTC
Example (CustomHook)
package main

import (
	"fmt"
	"reflect"

	"github.com/worldline-go/struct2"
)

func main() {
	type ColorGroup struct {
		Name  string `db:"name"`
		Count int    `db:"count"`
	}

	group := ColorGroup{
		Name: "DeepCore",
	}

	decoder := struct2.Decoder{
		TagName: "db",
		Hooks: []struct2.HookFunc{func(v reflect.Value) (interface{}, error) {
			if v.Kind() == reflect.String {
				return "str_" + v.Interface().(string), nil
			}

			return nil, struct2.ErrContinueHook
		}},
	}

	result := decoder.Map(group)

	fmt.Printf("%v", result["name"])
}
Output:

str_DeepCore

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrContinueHook = errors.New("continue to decode")

ErrContinueHook usable with HookFunc.

Functions

func Ptr2Concrete

func Ptr2Concrete(val interface{}) interface{}

Types

type Decoder

type Decoder struct {
	// Tagname to lookup struct's field tag.
	TagName string // default is 'struct'
	// Hooks function run before decode and enable to change of data.
	Hooks []HookFunc
}

Decoder is main struct of struct2, holds config and functions.

func (*Decoder) GetFields

func (d *Decoder) GetFields(s interface{}) []string

func (*Decoder) Map

func (d *Decoder) Map(s interface{}) map[string]interface{}

Map converts given struct to the map[string]interface{}.

func (*Decoder) MapOmitNested

func (d *Decoder) MapOmitNested(s interface{}) map[string]interface{}

MapOmitNested converts given struct to the map[string]interface{} without looking nested object.

type HookFunc

type HookFunc func(reflect.Value) (interface{}, error)

HookFunc get reflect.Value to modify custom in decoder.

type Hooker

type Hooker interface {
	Struct2Hook() interface{}
}

Hooker interface for structs.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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