structmap

package module
v0.0.0-...-df7b6ad Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2021 License: MIT Imports: 6 Imported by: 0

README


Logo

Contributors Issues License GoDoc Coverage

Decodifique um mapa em uma estrutura.
Explore a documentação »

Report Bug · Request Feature

Índice

Sobre o Projeto

Structmap é uma ferramenta que te permite preencher os valores de uma estrutura struct tendo como base um mapa map[string]interface{}.

Começando

Para usar o structmap basta seguir os seguintes passos.

  1. Instale como uma dependência:

    go get github.com/amulets/structmap
    
  2. Crie uma instầncia do structmap:

    sm := structmap.New()
    
  3. Adicione os comportamentos desejados:

    /**
     Única regra do structmap é que o primeiro comportamento
     precisa ser a descoberta de nome, caso não tenha,
     é preciso adicionar o name.Noop
    */
    sm.AddBehavior(name.Noop)
    
  4. Faça o decode do mapa na estrutura:

    //Sua estrutura
    type Person struct {
      Name string
      Age  int
    }
    
    // Declaração da estrutura e do mapa
    person := Person{}
    data := map[string]interface{}{
      "Name":"Joselito",
      "Age": 100,
    }
    // Decode passando as informações do mapa para a estrutura
    err := sm.Decode(data,&person)
    
  5. Pegue os valores pela estrutura:

    fmt.Println(person.Name)
    //Out: Joselito
    

Veja o código completo aqui

Uso

1. Definindo o nome(key) do campo

1.1 Tag

Código de exemplo

type Person struct {
  Name string `structmap:"my_name"`
}

...

data := map[string]interface{}{
  "my_name": "myName",
  "name": "Joselito",
}

...

sm.AddBehavior(name.FromTag("structmap"))
//Out: {Name:myName}

1.2 Snake case

Código de exemplo ou veja outros exemplo aqui.

type WordCase struct {
  SnakeCase string //-> snake_case
}

...

data := map[string]interface{}{
  "snake_case": "With Snake",
  "SnakeCase": "Without snake",
}

...

sm.AddBehavior(name.FromSnake)
//Out: {SnakeCase:With Snake}

1.3 Discovery

Código de exemplo

type Person struct {
  FirstName string `bson:"first_name"`
  LastName  string `json:"last_name"`
  Age       int
}

...

data := map[string]interface{}{
  "first_name": "Joselito",
  "last_name": "Otilesoj",
  "age":100,
}

...

sm.AddBehavior(name.Discovery(
  name.FromTag("bson"), //Pega o first_name
  name.FromTag("json"), //Pega o last_name
  name.FromSnake, //Pega o age
))
//Out: {FirstName:Joselito LastName:Otilesoj Age:100}

2. Definindo as flags

2.1 Required

Código de exemplo

type Person struct {
  FirstName string `structmap:",required"`
}

...

data := map[string]interface{}{}

...

sm.AddBehavior(flag.Required("structmap"))
//Out: error -> field FirstName is required

2.2 NoEmbedded

Código de exemplo

type Person struct {
  FirstName string
}

type Employee struct {
  Person `structmap:",noembedded"`
}
...

data := map[string]interface{}{
  "Person":map[string]interface{}{
    "FirstName":"myName",
  },
  "FirstName":"Joselito",
}

...

sm.AddBehavior(flag.NoEmbedded("structmap"))
//Out: {Person:{FirstName:myName}}

3. Definindo as conversões

Código de exemplo

type Person struct {
  FirstName string
  Age int
}

type Employee struct {
  Person
}
...

data := map[string]interface{}{
  "FirstName":"Joselito",
  "Age": "100", //A string será convertida para int
}

...

sm.AddBehavior(cast.ToType)
//Out: {Person:{FirstName:Joselito Age:100}}

Licença

Distribuído sob a licença MIT. Veja LICENSE para mais informações.

Projetos similares

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotIsToPointer = errors.New("to value cannot is a pointer")
	ErrNotIsStruct    = errors.New("value cannot is a struct")
)

All erros of StructMap

Functions

func WithDebug

func WithDebug(sm *StructMap)

WithDebug enable stack trace when have an panic

Types

type Behavior

type Behavior interface {
	Do(*FieldPart) error
}

Behavior implementation

type FieldFlags

type FieldFlags []string

FieldFlags of StructTag

func ParseTag

func ParseTag(tag string) (string, FieldFlags)

ParseTag return field tag value and flags tag is one of followings: "" "value" "value,flags" "value,flags,flags2" ",flags"

func (FieldFlags) Has

func (flags FieldFlags) Has(flagName string) bool

Has returns true if a flag is available in FieldFlags

type FieldPart

type FieldPart struct {
	Name       string
	Value      interface{}
	Type       reflect.Type
	Tag        reflect.StructTag
	Skip       bool
	IsEmbedded bool
}

FieldPart is a field representation

type OptionFunc

type OptionFunc func(*StructMap)

OptionFunc define options

func WithBehaviors

func WithBehaviors(behaviors ...Behavior) OptionFunc

WithBehaviors defines all logic of behaviors

type StructMap

type StructMap struct {
	// contains filtered or unexported fields
}

StructMap is a structmap

func New

func New(options ...OptionFunc) *StructMap

New instance of StructMap

func (*StructMap) Decode

func (sm *StructMap) Decode(from map[string]interface{}, to interface{}) (err error)

Decode map to struct

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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