Easily and dynamically generate maps from Go static structures

structomap Build Status Coverage Status GoDoc

This package helps you to transform your struct into map easily. It provides a structomap.Serializer interface implemented by the structomap.Base type which contains chainable function to add, remove or modify fields. The struct is transformed to a map[string]interface{} using the Transform(entity interface{}) method. It is then up to you to encode the result in JSON, XML or whatever you like.

Here is an example.

import "github.com/danhper/structomap"

type User struct {
    ID        int
    Email     string
    HideEmail bool
    FirstName string
    LastName  string
    CreatedAt time.Time
    UpdatedAt time.Time
}

currentTime := time.Date(2015, 05, 13, 15, 30, 0, 0, time.UTC)

user := User{
    ID: 1, Email: "[email protected]", FirstName: "Foo", LastName:  "Bar",
    HideEmail: true, CreatedAt: currentTime, UpdatedAt: currentTime,
}
userSerializer := structomap.New().
              UseSnakeCase().
              Pick("ID", "FirstName", "LastName", "Email").
              PickFunc(func(t interface{}) interface{} {
                  return t.(time.Time).Format(time.RFC3339)
              }, "CreatedAt", "UpdatedAt").
              OmitIf(func(u interface{}) bool {
                  return u.(User).HideEmail
              }, "Email").
              Add("CurrentTime", time.Date(2015, 5, 15, 17, 41, 0, 0, time.UTC)).
              AddFunc("FullName", func(u interface{}) interface{} {
                  return u.(User).FirstName + " " + u.(User).LastName
              })

userMap := userSerializer.Transform(user)
str, _ := json.MarshalIndent(userMap, "", "  ")
fmt.Println(string(str))

will give:

{
  "created_at": "2015-05-13T15:30:00Z",
  "current_time": "2015-05-15T17:41:00Z",
  "first_name": "Foo",
  "full_name": "Foo Bar",
  "id": 1,
  "last_name": "Bar",
  "updated_at": "2015-05-13T15:30:00Z"
}

Working with slices and arrays

You can also use structomap to transform slices and arrays, it will be applied to all elements. The only thing to do is to call TransformArray(entities) on a slice or an array. As TransformArray expects an interface{}, but in fact really wants a slice or an array, a second error argument is returned. If you do not want it, you can use MustTransformArray, which will panic instead of returning an error.

Here in an example reusing the above serializer.

otherUser := User{ID: 2, FirstName: "Ping", LastName: "Pong", CreatedAt: createdAt, UpdatedAt: createdAt}
users := []User{user, otherUser}
result, _ := userSerializer.TransformArray(users)
str, _ := json.MarshalIndent(result, "", "  ")
fmt.Println(string(str))

This will give:

[
  {
    "created_at": "2015-05-13T15:30:00Z",
    "current_time": "2015-05-15T17:41:00Z",
    "first_name": "Foo",
    "full_name": "Foo Bar",
    "id": 1,
    "last_name": "Bar",
    "updated_at": "2015-05-13T15:30:00Z"
  },
  {
    "created_at": "2015-05-13T15:30:00Z",
    "current_time": "2015-05-15T17:41:00Z",
    "email": "",
    "first_name": "Ping",
    "full_name": "Ping Pong",
    "id": 2,
    "last_name": "Pong",
    "updated_at": "2015-05-13T15:30:00Z"
  }
]

Choosing a key format

You can set the key format for the output map using UseSnakeCase(), UsePascalCase() or UseCamelCase() on the serializer object. You can also set the default case for all new serializers by using structomap.SetDefaultCase(structomap.SnakeCase) (structomap.CamelCase and structomap.PascalCase are also available). The init() function would be a good place to set this.

Building your own serializer

With structomap.Base as a base, you can easily build your serializer.

type UserSerializer struct {
  *structomap.Base
}

func NewUserSerializer() *UserSerializer {
  u := &UserSerializer{structomap.New()}
  u.Pick("ID", "CreatedAt", "UpdatedAt", "DeletedAt")
  return u
}

func (u *UserSerializer) WithPrivateInfo() *UserSerializer {
  u.Pick("Email")
  return u
}

userMap := NewUserSerializer().WithPrivateInfo().Transform(user)

Note that the u.Pick, and all other methods do modify the serializer, they do not return a new serializer each time. This is why it works even when ignoring u.Pick return value.

License

This is released under the MIT license. See the LICENSE file for more information.

Godoc

The full documentation is available at https://godoc.org/github.com/danhper/structomap.

Owner
Daniel Perez
software engineer interested in programming languages and functional programming
Daniel Perez
Similar Resources

Encode and decode Go (golang) struct types via protocol buffers.

protostructure protostructure is a Go library for encoding and decoding a struct type over the wire. This library is useful when you want to send arbi

Nov 15, 2022

Simple, specialised, and efficient binary marshaling

🔌 surge Documentation A library for fast binary (un)marshaling. Designed to be used in Byzantine networks, 🔌 surge never explicitly panics, protects

Oct 4, 2022

An optimal, byte-aligned, LZ+RLE hybrid encoder, designed to maximize decoding speed on NMOS 6502 and derived CPUs

An optimal, byte-aligned, LZ+RLE hybrid encoder, designed to maximize decoding speed on NMOS 6502 and derived CPUs

TSCrunch TSCrunch is an optimal, byte-aligned, LZ+RLE hybrid encoder, designed to maximize decoding speed on NMOS 6502 and derived CPUs, while keeping

Dec 21, 2022

Optimal implementation of ordered maps for Golang - ie maps that remember the order in which keys were inserted.

Goland Ordered Maps Same as regular maps, but also remembers the order in which keys were inserted, akin to Python's collections.OrderedDicts. It offe

Jan 3, 2023

Tutorial code for my video Learn to Use Basic Data Structures - Slices, Structs and Maps in Golang

Learn to Use Basic Data Structures - Slices, Structs and Maps in Golang Read text from a file and split into words. Introduction to slices / lists. Co

Jan 26, 2022

Static bit vector structures in Go

teivah/bitvector Overview A bit vector is an array data structure that compactly stores bits. This library is based on 5 static different data structu

Nov 6, 2022

yq lets you read YAML files easily on the terminal. You can find key/values easily

yq lets you read YAML files easily on the terminal. You can find key/values easily

yq yq lets you read YAML files easily on the terminal. You can find key/values easily. Motivation Reading yaml configurations for k8s file becomes ard

Nov 2, 2021

Generate flags by parsing structures

Flags based on structures. The sflags package uses structs, reflection and struct field tags to allow you specify command line options. It supports di

Nov 24, 2022

parse and generate XML easily in go

etree The etree package is a lightweight, pure go package that expresses XML in the form of an element tree. Its design was inspired by the Python Ele

Dec 30, 2022

parse and generate XML easily in go

etree The etree package is a lightweight, pure go package that expresses XML in the form of an element tree. Its design was inspired by the Python Ele

Dec 19, 2022

estruct traverses javascript projects and maps all the dependencies and relationships to a JSON. the output can be used to build network visualizations of the project and document the architecture.

estruct traverses javascript projects and maps all the dependencies and relationships to a JSON. the output can be used to build network visualizations of the project and document the architecture.

EStruct traverses javascript projects and maps all the dependencies and relationships to a JSON. The output can be used to build network visualizations of the project and document the architecture.

Jan 27, 2022

A Golang tool that does static analysis, unit testing, code review and generate code quality report.

A Golang tool that does static analysis, unit testing, code review and generate code quality report.

goreporter A Golang tool that does static analysis, unit testing, code review and generate code quality report. This is a tool that concurrently runs

Jan 8, 2023

LazySSH is an SSH server that acts as a jump host only, and dynamically starts temporary virtual machines.

LazySSH is an SSH server that acts as a jump host only, and dynamically starts temporary virtual machines. If you find yourself briefly starti

Dec 11, 2022

System resource usage profiler tool which regularly takes snapshots of the memory and CPU load of one or more running processes so as to dynamically build up a profile of their usage of system resources.

System resource usage profiler tool which regularly takes snapshots of the memory and CPU load of one or more running processes so as to dynamically build up a profile of their usage of system resources.

Vegeta is a system resource usage tracking tool built to regularly take snapshots of the memory and CPU load of one or more running processes, so as to dynamically build up a profile of their usage of system resources.

Jan 16, 2022

Server for hosting a Munki repository and dynamically generating manifests

About munki-server is an all-in-one server to deploy Munki with three main parts: HTTP file server for Munki clients Simple dynamic manifest generatio

Dec 7, 2021

OcppManager-go - A library for dynamically managing OCPP configuration (variables). It can read, update, and validate OCPP variables.

🔌 ocppManager-go A library for dynamically managing OCPP configuration (variables). It can read, update, and validate OCPP variables. Currently, only

Jan 3, 2022

Ipctl - Listen to IP change and change your DNS' records dynamically

ipctl Listen to IP change and change your DNS' records dynamically Table of cont

Feb 17, 2022

A CLI Tool to easily generate your Terraform configuration

Tf Tf is a command line tool to easily generate your Terraform configuration with an interactive prompt. Inspiration Boredom in Covid-19 Installation

Sep 30, 2022
Comments
  • go mod is not work with structomap

    go mod is not work with structomap

    I am trying to use go modules. But my packages are giving error after go build command.

    my code

    import (
    	"github.com/danhper/structomap"
    )
    
    // Serializer used in constructing maps to output JSON
    type Serializer struct {
    	*structomap.Base
    }
    

    output

    ./models.go:<line number>: imported and not used: "github.com/tuvistavie/structomap" as serializer
    ./models.go:<line number>: undefined: structomap
    
Go package for dealing with maps, slices, JSON and other data.

Objx Objx - Go package for dealing with maps, slices, JSON and other data. Get started: Install Objx with one line of code, or update it with another

Dec 27, 2022
Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Jan 1, 2023
auto-generate capnproto schema from your golang source files. Depends on go-capnproto-1.0 at https://github.com/glycerine/go-capnproto

bambam: auto-generate capnproto schema from your golang source files. Adding capnproto serialization to an existing Go project used to mean writing a

Sep 27, 2022
Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

bel Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC bel is used in production in https://gitpod.io. Getting started be

Oct 23, 2022
Cap'n Proto library and parser for go. This is go-capnproto-1.0, and does not have rpc. See https://github.com/zombiezen/go-capnproto2 for 2.0 which has rpc and capabilities.

Version 1.0 vs 2.0 Update 2015 Sept 20: Big news! Version 2.0 of the go-bindings, authored by Ross Light, is now released and newly available! It feat

Nov 29, 2022
csvutil provides fast and idiomatic mapping between CSV and Go (golang) values.
csvutil provides fast and idiomatic mapping between CSV and Go (golang) values.

csvutil Package csvutil provides fast and idiomatic mapping between CSV and Go (golang) values. This package does not provide a CSV parser itself, it

Jan 6, 2023
Encode and decode binary message and file formats in Go

Encode and Decode Binary Formats in Go This module wraps the package encoding/binary of the Go standard library and provides the missing Marshal() and

Dec 22, 2022
Some Golang types based on builtin. Implements interfaces Value / Scan and MarshalJSON / UnmarshalJSON for simple working with database NULL-values and Base64 encoding / decoding.

gotypes Some simple types based on builtin Golang types that implement interfaces for working with DB (Scan / Value) and JSON (Marshal / Unmarshal). N

Feb 12, 2022
Asn.1 BER and DER encoding library for golang.

WARNING This repo has been archived! NO further developement will be made in the foreseen future. asn1 -- import "github.com/PromonLogicalis/asn1" Pac

Nov 14, 2022
idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]

go-codec This repository contains the go-codec library, the codecgen tool and benchmarks for comparing against other libraries. This is a High Perform

Dec 19, 2022