mapper

package module
v0.7.14 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2024 License: MIT Imports: 10 Imported by: 32

README

devfeel/mapper

A simple and easy go tools for auto mapper struct to map, struct to struct, slice to slice, map to slice, map to json.

1. Install

go get -u github.com/devfeel/mapper

2. Getting Started

Traditional Usage

package main

import (
	"fmt"
	"github.com/devfeel/mapper"
)

type (
	User struct {
		Name string
		Age  int
		Id   string `mapper:"_id"`
		AA   string `json:"Score"`
		Time time.Time
	}

	Student struct {
		Name  string
		Age   int
		Id    string `mapper:"_id"`
		Score string
	}

	Teacher struct {
		Name  string
		Age   int
		Id    string `mapper:"_id"`
		Level string
	}
)

func init() {
	mapper.Register(&User{})
	mapper.Register(&Student{})
}

func main() {
	user := &User{}
	userMap := &User{}
	teacher := &Teacher{}
	student := &Student{Name: "test", Age: 10, Id: "testId", Score: "100"}
	valMap := make(map[string]interface{})
	valMap["Name"] = "map"
	valMap["Age"] = 10
	valMap["_id"] = "x1asd"
	valMap["Score"] = 100
	valMap["Time"] = time.Now()

	mapper.Mapper(student, user)
	mapper.AutoMapper(student, teacher)
	mapper.MapperMap(valMap, userMap)

	fmt.Println("student:", student)
	fmt.Println("user:", user)
	fmt.Println("teacher", teacher)
	fmt.Println("userMap:", userMap)
}

执行main,输出:

student: &{test 10 testId 100}
user: &{test 10 testId 100 0001-01-01 00:00:00 +0000 UTC}
teacher &{test 10 testId }
userMap: &{map 10 x1asd 100 2017-11-20 13:45:56.3972504 +0800 CST m=+0.006004001}

Object Usage

package main

import (
  "fmt"
  "github.com/devfeel/mapper"
)

type (
  User struct {
    Name  string `json:"name" mapper:"name"`
    Class int    `mapper:"class"`
    Age   int    `json:"age" mapper:"-"`
  }

  Student struct {
    Name  string `json:"name" mapper:"name"`
    Class int    `mapper:"class"`
    Age   []int  `json:"age" mapper:"-"`
  }
)

func main() {
  user := &User{Name: "shyandsy", Class: 1, Age: 10}
  student := &Student{}

  // create mapper object
  m := mapper.NewMapper()

  // in the version < v0.7.8, we will use field name as key when mapping structs
  // we keep it as default behavior in this version
  m.SetEnableIgnoreFieldTag(true)

  student.Age = []int{1}

  // disable the json tag
  m.SetEnabledJsonTag(false)

  // student::age should be 1
  m.Mapper(user, student)

  fmt.Println("user:")
  fmt.Println(user)
  fmt.Println("student:")
  fmt.Println(student)
}

执行main,输出:

user:
&{shyandsy 1 10}
student:
&{shyandsy 1 [1]}

Features

  • 支持不同结构体相同名称相同类型字段自动赋值,使用Mapper
  • 支持不同结构体Slice的自动赋值,使用MapperSlice
  • 支持字段为结构体时的自动赋值
  • 支持struct到map的自动映射赋值,使用Mapper
  • 支持map到struct的自动映射赋值,使用MapperMap
  • 支持map到struct slice的自动赋值,使用MapToSlice
  • 支持map与json的互相转换
  • 支持Time与Unix自动转换
  • 支持tag标签,tag关键字为 mapper
  • 兼容json-tag标签
  • 当tag为"-"时,将忽略tag定义,使用struct field name
  • 无需手动Register struct,内部自动识别
  • 支持开启关闭
    • SetEnabledTypeChecking(bool) // 类型检查
    • IsEnabledTypeChecking
    • SetEnabledMapperTag // mapper tag
    • IsEnabledMapperTag
    • SetEnabledJsonTag // json tag
    • IsEnabledJsonTag
    • SetEnabledAutoTypeConvert // auto type convert
    • IsEnabledAutoTypeConvert
    • SetEnabledMapperStructField // mapper struct field
    • IsEnabledMapperStructField

Documentation

Index

Constants

View Source
const (
	IgnoreTagValue         = "-"
	CompositeFieldTagValue = "composite-field"
)

Variables

This section is empty.

Functions

func AutoMapper

func AutoMapper(fromObj, toObj interface{}) error

AutoMapper mapper and set value from struct fromObj to toObj support auto register struct

func CheckExistsField

func CheckExistsField(elem reflect.Value, fieldName string) (realFieldName string, exists bool)

CheckExistsField check field is exists by name

func CheckIsTypeWrapper

func CheckIsTypeWrapper(value reflect.Value) bool

CheckIsTypeWrapper check value is in type wrappers

func GetFieldName

func GetFieldName(objElem reflect.Value, index int) string

GetFieldName get fieldName with ElemValue and index if config tag string, return tag value

func GetTimeJSONFormat

func GetTimeJSONFormat() string

func GetTypeName

func GetTypeName(obj interface{}) string

GetTypeName get type name

func IsEnabledCustomTag added in v0.7.13

func IsEnabledCustomTag() bool

func JsonToMap

func JsonToMap(body []byte, toMap *map[string]interface{}) error

JsonToMap mapper from json []byte to map[string]interface{}

func MapToJson

func MapToJson(fromMap map[string]interface{}) ([]byte, error)

MapToJson mapper from map[string]interface{} to json []byte

func MapToSlice

func MapToSlice(fromMap map[string]interface{}, toSlice interface{}) error

MapToSlice mapper from map[string]interface{} to a slice of any type's ptr toSlice must be a slice of any type.

func Mapper

func Mapper(fromObj, toObj interface{}) error

Mapper mapper and set value from struct fromObj to toObj not support auto register struct

func MapperMap

func MapperMap(fromMap map[string]interface{}, toObj interface{}) error

MapperMap mapper and set value from map to object support auto register struct now support field type: 1.reflect.Bool 2.reflect.String 3.reflect.Int8\16\32\64 4.reflect.Uint8\16\32\64 5.reflect.Float32\64 6.time.Time

func MapperMapSlice

func MapperMapSlice(fromMaps map[string]map[string]interface{}, toSlice interface{}) error

MapperMapSlice mapper from map[string]map[string]interface{} to a slice of any type's ptr toSlice must be a slice of any type. Deprecated: will remove on v1.0, please use MapToSlice instead

func MapperSlice

func MapperSlice(fromSlice, toSlice interface{}) error

MapperSlice mapper from slice of struct to a slice of any type fromSlice and toSlice must be a slice of any type.

func PackageVersion

func PackageVersion() string

func Register

func Register(obj interface{}) error

Register register struct to init Map

func SetCustomTagName added in v0.7.13

func SetCustomTagName(tagName string)

SetCustomTagName

func SetEnableFieldIgnoreTag added in v0.7.10

func SetEnableFieldIgnoreTag(isEnabled bool)

SetEnableFieldIgnoreTag set the enabled flag for the ignored tag in the version < 0.7.8, we use field name as the key when mapping structs if field tag is "-" from 0.7.8, we add switch enableFieldIgnoreTag which is false in default if caller enable this flag, the field will be ignored in the mapping process

func SetEnabledAutoTypeConvert

func SetEnabledAutoTypeConvert(isEnabled bool)

SetEnabledAutoTypeConvert set enabled flag for auto type convert if set true, field will auto convert in Time and Unix default is true

func SetEnabledCustomTag added in v0.7.13

func SetEnabledCustomTag(isEnabled bool)

SetEnabledCustomTag set enabled flag for set custom tag name if set true and set customTagName, the custom tag will be check during mapping's GetFieldName default is false

func SetEnabledJsonTag

func SetEnabledJsonTag(isEnabled bool)

SetEnabledJsonTag set enabled flag for 'Json' tag check if set true, 'Json' tag will be check during mapping's GetFieldName default is true

func SetEnabledMapperStructField

func SetEnabledMapperStructField(isEnabled bool)

SetEnabledMapperStructField set enabled flag for MapperStructField if set true, the reflect.Struct field will auto mapper must follow premises: 1. fromField and toField type must be reflect.Struct and not time.Time 2. fromField and toField must be not same type default is enabled

func SetEnabledMapperTag

func SetEnabledMapperTag(isEnabled bool)

SetEnabledMapperTag set enabled flag for 'Mapper' tag check if set true, 'Mapper' tag will be check during mapping's GetFieldName default is true

func SetEnabledTypeChecking

func SetEnabledTypeChecking(isEnabled bool)

SetEnabledTypeChecking set enabled flag for TypeChecking if set true, the field type will be checked for consistency during mapping default is false

func SetTimeJSONFormat

func SetTimeJSONFormat(format string)

func TimeToUnix

func TimeToUnix(t time.Time) int64

TimeToUnix transform time to Unix time, the number of seconds elapsed

func TimeToUnixLocation

func TimeToUnixLocation(t time.Time, location string) (int64, error)

TimeToUnixLocation transform time to Unix time with time location location like "Asia/Shanghai"

func ToInt64

func ToInt64(value interface{}) (d int64)

ToInt64 interface to int64

func ToString

func ToString(value interface{}, args ...int) (s string)

ToString interface to string

func UnixToTime

func UnixToTime(tt int64) time.Time

UnixToTime transform Unix time to local Time

func UnixToTimeLocation

func UnixToTimeLocation(tt int64, location string) (time.Time, error)

UnixToTimeLocation transform Unix time to local Time with time location location like "Asia/Shanghai"

func UseWrapper

func UseWrapper(w TypeWrapper)

UseWrapper register a type wrapper

Types

type BaseTypeWrapper

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

func (*BaseTypeWrapper) SetNext

func (bm *BaseTypeWrapper) SetNext(m TypeWrapper)

type Convert

type Convert string

Convert is the target string

func (Convert) Bool

func (f Convert) Bool() (bool, error)

Bool string to bool

func (*Convert) Clear

func (f *Convert) Clear()

Clear string

func (Convert) Exist

func (f Convert) Exist() bool

Exist check string exist

func (Convert) Float32

func (f Convert) Float32() (float32, error)

Float32 string to float32

func (Convert) Float64

func (f Convert) Float64() (float64, error)

Float64 string to float64

func (Convert) Int

func (f Convert) Int() (int, error)

Int string to int

func (Convert) Int16

func (f Convert) Int16() (int16, error)

Int16 string to int16

func (Convert) Int32

func (f Convert) Int32() (int32, error)

Int32 string to int32

func (Convert) Int64

func (f Convert) Int64() (int64, error)

Int64 string to int64

func (Convert) Int8

func (f Convert) Int8() (int8, error)

Int8 string to int8

func (*Convert) Set

func (f *Convert) Set(v string)

Set string

func (Convert) String

func (f Convert) String() string

String string to string

func (Convert) Uint

func (f Convert) Uint() (uint, error)

Uint string to uint

func (Convert) Uint16

func (f Convert) Uint16() (uint16, error)

Uint16 string to uint16

func (Convert) Uint32

func (f Convert) Uint32() (uint32, error)

Uint32 string to uint32

func (Convert) Uint64

func (f Convert) Uint64() (uint64, error)

Uint64 string to uint64

func (Convert) Uint8

func (f Convert) Uint8() (uint8, error)

Uint8 string to uint8

type IMapper added in v0.7.10

type IMapper interface {
	Mapper(fromObj, toObj interface{}) error
	AutoMapper(fromObj, toObj interface{}) error
	MapperMap(fromMap map[string]interface{}, toObj interface{}) error
	MapToSlice(fromMap map[string]interface{}, toSlice interface{}) error
	MapperMapSlice(fromMaps map[string]map[string]interface{}, toSlice interface{}) error
	MapperSlice(fromSlice, toSlice interface{}) error
	MapToJson(fromMap map[string]interface{}) ([]byte, error)
	JsonToMap(body []byte, toMap *map[string]interface{}) error

	Register(obj interface{}) error
	UseWrapper(w TypeWrapper)

	GetTypeName(obj interface{}) string
	GetFieldName(objElem reflect.Value, index int) string
	GetCustomTagName() string
	GetDefaultTimeWrapper() *TimeWrapper

	CheckExistsField(elem reflect.Value, fieldName string) (realFieldName string, exists bool)
	CheckIsTypeWrapper(value reflect.Value) bool

	SetEnabledTypeChecking(isEnabled bool)
	IsEnabledTypeChecking() bool

	SetEnabledMapperTag(isEnabled bool)
	IsEnabledMapperTag() bool

	SetEnabledJsonTag(isEnabled bool)
	IsEnabledJsonTag() bool

	SetEnabledCustomTag(isEnabled bool)
	IsEnabledCustomTag() bool
	SetCustomTagName(tagName string)

	SetEnabledAutoTypeConvert(isEnabled bool)
	IsEnabledAutoTypeConvert() bool

	SetEnabledMapperStructField(isEnabled bool)
	IsEnabledMapperStructField() bool

	SetEnableFieldIgnoreTag(isEnabled bool)
	IsEnableFieldIgnoreTag() bool
}

func NewMapper added in v0.7.10

func NewMapper(opts ...Option) IMapper

type JSONTime

type JSONTime time.Time

func (JSONTime) MarshalJSON

func (t JSONTime) MarshalJSON() ([]byte, error)

func (JSONTime) String

func (t JSONTime) String() string

func (*JSONTime) UnmarshalJSON

func (t *JSONTime) UnmarshalJSON(data []byte) (err error)

type Option added in v0.7.14

type Option func(*Setting)

Option 用于设置 Config 结构体的字段。

func CAutoTypeConvert added in v0.7.14

func CAutoTypeConvert(isEnabled bool) Option

func CCustomTag added in v0.7.14

func CCustomTag(isEnabled bool) Option

func CCustomTagName added in v0.7.14

func CCustomTagName(tagName string) Option

func CFieldIgnoreTag added in v0.7.14

func CFieldIgnoreTag(isEnabled bool) Option

func CJsonTag added in v0.7.14

func CJsonTag(isEnabled bool) Option

func CMapperStructField added in v0.7.14

func CMapperStructField(isEnabled bool) Option

func CMapperTag added in v0.7.14

func CMapperTag(isEnabled bool) Option

CMapperTag set EnabledMapperTag value

Default value: true

func CTypeChecking added in v0.7.14

func CTypeChecking(isEnabled bool) Option

CTypeChecking set EnabledTypeChecking value

Default value: false

type Setting added in v0.7.14

type Setting struct {
	EnabledTypeChecking      bool
	EnabledMapperStructField bool
	EnabledAutoTypeConvert   bool
	EnabledMapperTag         bool
	EnabledJsonTag           bool
	EnabledCustomTag         bool
	CustomTagName            string

	// in the version < 0.7.8, we use field name as the key when mapping structs if field tag is "-"
	// from 0.7.8, we add switch enableIgnoreFieldTag which is false in default
	// if caller enable this flag, the field will be ignored in the mapping process
	EnableFieldIgnoreTag bool
}

func NewSetting added in v0.7.14

func NewSetting(opts ...Option) *Setting

NewSetting create new setting with multi option

type TimeWrapper

type TimeWrapper struct {
	BaseTypeWrapper
}

func NewTimeWrapper

func NewTimeWrapper() *TimeWrapper

func (*TimeWrapper) IsType

func (w *TimeWrapper) IsType(value reflect.Value) bool

type TypeWrapper

type TypeWrapper interface {
	IsType(value reflect.Value) bool
	SetNext(m TypeWrapper)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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