structo

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2025 License: MIT Imports: 14 Imported by: 0

README

Structo 🏗️

Go library for struct serialization, diffing, change tracking, and default injection with nested struct, pointer, slice, and encoding support.


✨ Features

  • ✅ Encode/decode struct to string or binary
  • 🔄 Flatten dan unflatten nested struct
  • 📆 Inject default values to struct
  • 🕵️ Struct diffing and history tracking
  • ⟳ Copy between structs with different shapes

📦 Installations

go get github.com/Lucifer07/Structo

🚀 Example

Struct Sample
type Address struct {
	City    string `json:"city"`
	ZipCode string `json:"zipCode"`
}

type Metadata struct {
	Active  bool   `json:"active"`
	Version string `json:"version"`
}

type User struct {
	ID       int
	Name     string
	Email    *string
	Tags     []string
	Metadata Metadata
	Address  *Address
}

🔐 Encode & Decode
conv := structo.NewConverter()
encoded := conv.EncodeToString(user)
conv.DecodeFromString(encoded, &user)

🧱 Binary Encode & Decode
bin := conv.StructToBinary(user)
conv.BinaryToStruct(bin, &user)

🔐 Safe Encode
encoded := conv.EncodeToStringSafe(user)
conv.DecodeFromStringSafe(encoded, &user)

🧬 Flatten & Unflatten
flat := structo.Flatten(user)
// map[string]any: {"Name":"Jane", "Address.City":"Jakarta", ...}

var u User
structo.Unflatten(flat, &u)

🗓️ Diff Struct
diff, _ := structo.Diff(oldUser, newUser)
for field, values := range diff {
	fmt.Printf("%s: %v -> %v\n", field, values[0], values[1])
}

📊 Track Changes (Add, Remove, Change)
changes, _ := structo.TrackWithHistory(oldUser, newUser)
for field, res := range changes {
	switch res.Action {
	case structo.Add:
		fmt.Printf("%s: appended %v\n", field, res.Data.GetData())
	case structo.Remove:
		fmt.Printf("%s: removed %v\n", field, res.Data.GetData())
	case structo.Change:
		data := res.Data.GetData().([]any)
		fmt.Printf("%s: changed from %v to %v\n", field, data[0], data[1])
	}
}

⟳ Copy Struct to a Different Shape
var external ExternalUser
structo.Copy(&external, user)

⚙️ Inject Default Values
type Profile struct {
	Name  string `default:"Anonymous"`
	Age   int    `default:"18"`
	Email string `default:"default@example.com"`
}
var p Profile
structo.InjectDefaults(&p)
// p.Name = "Anonymous", etc.

📁 Full Example

view the example/main.go file for full example, runnable example.


📜 Lisensi

MIT © Lucifer07


💡 Contributions

Contributions are welcome! Feel free to open issues and pull requests to improve Structo.


🔥 Enjoy fast and secure struct serialization with Structo!

Documentation

Overview

Package structo provides functionality for encoding and decoding Go structures to and from binary data and string representations, including optional encryption.

Index

Constants

This section is empty.

Variables

View Source
var (
	TimestampToTime = TypeConverter{
		DstType: timestamppb.Timestamp{},
		SrcType: time.Time{},
		Fn: func(src interface{}) (interface{}, error) {
			return *timestamppb.New(src.(time.Time)), nil
		},
	}

	TimeToTimestamp = TypeConverter{
		DstType: time.Time{},
		SrcType: timestamppb.Timestamp{},
		Fn: func(src interface{}) (interface{}, error) {
			return src.(*timestamppb.Timestamp).AsTime(), nil
		},
	}

	DefaultProtoConverters = []TypeConverter{
		TimestampToTime,
		TimeToTimestamp,
	}
)

Functions

func Copy

func Copy(toValue interface{}, fromValue interface{}) (err error)

Copy things.

func CopyWithOption

func CopyWithOption(toValue interface{}, fromValue interface{}, opt CopyOption) (err error)

Copy With Option

func Diff

func Diff(oldStruct, newStruct interface{}) (map[string][2]interface{}, error)

Diff returns a map of field names and their [old, new] values that differ.

func Flatten

func Flatten(data interface{}) map[string]interface{}

Flatten returns a flat map of a struct's fields using dot notation.

func InjectDefaults

func InjectDefaults(ptr interface{}) error

InjectDefaults.

func TrackWithHistory

func TrackWithHistory(oldStruct, newStruct interface{}) (map[string]result, error)

TrackWithHistory returns a map of field paths and their detected actions

func Unflatten

func Unflatten(flatMap map[string]interface{}, result interface{}) error

Unflatten sets values in a struct based on keys in a flat map (supports nested dot notation).

Types

type Actions

type Actions string

Actions represent the type of change

const (
	Add    Actions = "add"
	Remove Actions = "remove"
	Change Actions = "change"
)

type Converter

type Converter interface {
	StructToBinary(data interface{}) ([]byte, error)
	BinaryToStruct(data []byte, result interface{}) error
	EncodeToString(data interface{}) (string, error)
	DecodeFromString(data string, result interface{}) error
	EncodeToStringSafe(data interface{}) (string, error)
	DecodeFromStringSafe(data string, result interface{}) error
}

Converter defines the interface for encoding and decoding structures.

func NewConverter

func NewConverter() Converter

NewConverter creates and returns a new instance of ConverterImpl.

type CopyOption

type CopyOption struct {
	// setting this value to true will ignore copying zero values of all the fields, including bools, as well as a
	// struct having all it's fields set to their zero values respectively (see IsZero() in reflect/value.go)
	IgnoreEmpty   bool
	CaseSensitive bool
	DeepCopy      bool
	Converters    []TypeConverter
	// Custom field name mappings to copy values with different names in `fromValue` and `toValue` types.
	// Examples can be found in `copier_field_name_mapping_test.go`.
	FieldNameMapping []FieldNameMapping
}

Option sets copy options

func WithOptionsProtobuf

func WithOptionsProtobuf(options ...CopyOption) CopyOption

type FieldNameMapping

type FieldNameMapping struct {
	SrcType interface{}
	DstType interface{}
	Mapping map[string]string
}

type TypeConverter

type TypeConverter struct {
	SrcType interface{}
	DstType interface{}
	Fn      func(src interface{}) (dst interface{}, err error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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