• Stars
    star
    141
  • Rank 250,838 (Top 6 %)
  • Language
    Go
  • License
    MIT License
  • Created almost 9 years ago
  • Updated almost 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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.

More Repositories

1

atomic-chrome

Edit Chrome textareas in Atom
JavaScript
917
star
2

fundle

A minimalist package manager for fish shell
Shell
363
star
3

opencov

Open source code coverage history webapp
Elixir
311
star
4

fish-ssh-agent

Shell
288
star
5

ex_cli

User friendly CLI apps for Elixir
Elixir
214
star
6

python-i18n

Easy to use i18n library for Python
Python
201
star
7

pushex

Push notifications for Elixir
Elixir
104
star
8

elixir-browser

Browser detection for Elixir
Elixir
95
star
9

atomic-chrome-atom

Edit Chrome textareas in Atom
CoffeeScript
93
star
10

elixir-temp

Temporary files and directories for Elixir
Elixir
74
star
11

plug-navigation-history

Elixir plug to keep navigation history
Elixir
69
star
12

elixir-git-cli

A simple interface to Git CLI for Elixir
Elixir
68
star
13

phoenix-active-link

Elixir/Phoenix view helper to manage "active" state of a link
Elixir
63
star
14

elixir-web-push-encryption

Elixir implementation of Web Push Payload encryption.
Elixir
54
star
15

bigcode-tools

Set of tools to help working with "Big Code"
Python
42
star
16

rust-simple-nn

Simple neural network implementation in Rust
Rust
33
star
17

seedex

Seed data generation for Ecto
Elixir
29
star
18

securerandom

Go
25
star
19

evm-analyzer

Code for Smart Contract Vulnerabilities: Vulnerable Does Not Imply Exploited
OCaml
22
star
20

fish-fastdir

Fast directory navigation for fish
Shell
19
star
21

asdf-exec

Native command to run asdf shims
Go
16
star
22

node-git-cli

Simple CLI like git interface for Node.
CoffeeScript
16
star
23

suplearn-clone-detection

Cross language clone detection using supervised learning
Python
15
star
24

defi-plf-analysis

Code and data for the paper: DeFi Protocols for Loanable Funds: Interest Rates, Liquidity and Market Efficiency
Jupyter Notebook
13
star
25

scalog

Datalog implementation in Scala.
Scala
12
star
26

atom-align-regexp

Regexp based alignment for Atom
JavaScript
11
star
27

koa-police

Policy based authentication library for Koa
JavaScript
9
star
28

fontawesome-icons-list

Fontawesome icons list
JavaScript
9
star
29

blockchain-analyzer

Tool to fetch and analyze blockchain transactions
Go
9
star
30

fish-kubectl

Shell
8
star
31

oh-my-fish-core

oh-my-fish core library extracted
Shell
7
star
32

sigma-bower

Bower repository for SigmaJS
JavaScript
6
star
33

ecto-secure-password

has_secure_password for Ecto models
Elixir
5
star
34

dotfiles

TeX
5
star
35

ocaml-monads

OCaml
5
star
36

fish-completion-helpers

Fish helper functions to simplify completions
Shell
5
star
37

wedding

Simple webapp to manage guests and invitations for my wedding with Ai.
Ruby
4
star
38

go-sqs-client

Go
4
star
39

ethereum-tools

Python
4
star
40

flashcards-cli

Text-based flashcards
OCaml
3
star
41

phd-thesis

TeX
3
star
42

deepsentence

ๅ’Œๆ–‡ๆ–‡ๆ›ธใ‹ใ‚‰ใฎ่ฆ็‚นๆŠฝๅ‡บ
Python
3
star
43

scala-simple-compiler

Scala
3
star
44

code-battle

HTML
3
star
45

simple-bitcoin-parser

Simple Python Bitcoin parser/formatter implementation
Python
3
star
46

fish-nvm

nvm wrapper for fish
Shell
3
star
47

meditable

WIP: markdown <-> html
JavaScript
2
star
48

fish-asdf

fish plugin for asdf vm
Shell
2
star
49

projare

Sample app using Elixir, Phoenix and RiotJS
JavaScript
2
star
50

sublime-file-commands

Commands to work with files in Sublime Text
Python
2
star
51

advent-2022

Rust
2
star
52

elixir-logger-sample

Elixir
2
star
53

websocket-rails-bower

1
star
54

master-thesis

A study of machine learning approaches to cross-language code clone detection
TeX
1
star
55

advent-2020

Haskell
1
star
56

advent-2023

F#
1
star
57

vim-config

Vim Script
1
star
58

go-ethereum-customized

Fork of the official geth client
Go
1
star
59

word-frequency-analyzer

Simple word frequency analyzer with JavaFX rendering.
Scala
1
star
60

bachelor-thesis

Repository for my bachelor thesis
TeX
1
star
61

js-easy-params

Decorator for JS functions with optional arguments
JavaScript
1
star
62

scala-x-server

System to run an X server in a web browser
Scala
1
star
63

jsurl_ex

Elixir
1
star
64

tokyo-ex-1-slides

HTML
1
star
65

erlang-sqs-client

Erlang
1
star
66

sublime-rails-status-snippets

ST2/3 snippets for HTTP codes symbols in RoR
Python
1
star
67

revealjs-jade-starter

HTML
1
star
68

ansible-exrm

1
star
69

koa-police-jwt

JWT strategy for koa-police
JavaScript
1
star
70

django-twitter-auth-sample

Python
1
star
71

aleth

C++
1
star