inflate

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

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

Go to latest
Published: Dec 19, 2022 License: Apache-2.0 Imports: 14 Imported by: 3

README

inflate

A Golang reflection package on steroids

Documentation License Build Status Coverage Go Report Card

Motivation

The project is motivated from the fact that there are no packages that convert values based on different criteria:

  • Convert values based on OpenAPI parameters serialization format
  • Sets the default value defined by tag attribute
  • Sets the structure fields from another structure or map by using tag attribute

The library works in greedy manner. It tries to convert incompatible values as much as it can. Thanks for the inspiration to the contributors of the following projects:

Installation

$ go get -u github.com/phogolabs/inflate

Usage

The basic usage of the package gives some handy features.

If you want to convert a value from one type to another, you can use the following function:

type Order struct {
  ID string `field:"order_id"`
}

type OrderItem struct {
  OrderID string `field:"order_id"`
}
source := &Order{ID: "0000123"}
target := &OrderItem{}

if err := inflate.Set(target, source); err != nil {
  panic(err)
}

fmt.Printf("%+v", target)

// Output: &{OrderID:0000123}

You can use the package to set the default values (if they are not set):

type Address struct {
	City    string `json:"city"`
	Country string `json:"country"`
}

type Profile struct {
	Name    string  `default:"John"`
	Address Address `default:"{\"city\":\"London\",\"country\":\"UK\"}"`
}

profile := &Profile{}

if err := inflate.SetDefault(profile); err != nil {
	panic(err)
}

fmt.Printf("%+v", profile)

// Output:
// &{Name:John Address:{City:London Country:UK}}

The package supports serialization of parameters in OpenAPI spec format. For more advanced examples, please read the online documentation.

Contributing

We are open for any contributions. Just fork the project.

Documentation

Index

Examples

Constants

View Source
const (
	// OptionSimple is the simple opt
	OptionSimple = "simple"
	// OptionForm is the form opt
	OptionForm = "form"
	// OptionLabel is the simple opt
	OptionLabel = "label"
	// OptionMatrix is the simple opt
	OptionMatrix = "matrix"
	// OptionExplode is the simple opt
	OptionExplode = "explode"
	// OptionDeepObject is the simple opt
	OptionDeepObject = "deep-object"
	// OptionSpaceDelimited is the space-delimited opt
	OptionSpaceDelimited = "space-delimited"
	// OptionPipeDelimited is the pipe-delimited opt
	OptionPipeDelimited = "pipe-delimited"
)

Variables

This section is empty.

Functions

func Set

func Set(target, source interface{}) error

Set sets the value

func SetDefault

func SetDefault(target interface{}) error

SetDefault set the default values

Types

type Array

type Array struct {
	TagName string
	Elem    reflect.Type
	Value   reflect.Value
}

Array works with slices and arrays

func ArrayOf

func ArrayOf(tagName string, value reflect.Value) *Array

ArrayOf returns an array / slice

func MakeArrayOf

func MakeArrayOf(tagName string, value reflect.Value) *Array

MakeArrayOf returns an array / slice

func (*Array) Append

func (arr *Array) Append(value reflect.Value)

Append appends an item to the array

type Context

type Context struct {
	Field  string
	Type   reflect.Type
	IsZero bool
	Tag    *Tag
}

Context is the context

type Converter

type Converter struct {
	TagName string
}

Converter represents a decoder

func (*Converter) Convert

func (d *Converter) Convert(from, to interface{}) error

Convert converts a value to another value

type CookieProvider

type CookieProvider struct {
	Cookies []*http.Cookie
}

CookieProvider represents a parameter provider that fetches values from incoming request's cookies

func (*CookieProvider) Value

func (p *CookieProvider) Value(ctx *Context) (interface{}, error)

Value returns a primitive value

type Decoder

type Decoder struct {
	TagName   string
	Provider  ValueProvider
	Converter ValueConverter
}

Decoder decodes the values from given source

Example (Default)
package main

import (
	"fmt"

	"github.com/phogolabs/inflate"
)

func main() {
	type Address struct {
		City    string `json:"city"`
		Country string `json:"country"`
	}

	type Profile struct {
		Name    string  `default:"John"`
		Address Address `default:"{\"city\":\"London\",\"country\":\"UK\"}"`
	}

	profile := &Profile{}

	if err := inflate.SetDefault(profile); err != nil {
		panic(err)
	}

	fmt.Printf("%+v", profile)

}
Output:

&{Name:John Address:{City:London Country:UK}}
Example (Header)
package main

import (
	"fmt"
	"net/http"

	"github.com/phogolabs/inflate"
)

func main() {
	type Tag struct {
		RequestID string `header:"X-Request-ID"`
	}

	header := http.Header{}
	header.Set("X-Request-ID", "123456")

	tag := &Tag{}

	if err := inflate.NewHeaderDecoder(header).Decode(tag); err != nil {
		panic(err)
	}

	fmt.Printf("%+v", tag)

}
Output:

&{RequestID:123456}
Example (Path)
package main

import (
	"fmt"

	"github.com/go-chi/chi"
	"github.com/phogolabs/inflate"
)

func main() {
	type Member struct {
		ID string `path:"id"`
	}

	param := &chi.RouteParams{}
	param.Keys = append(param.Keys, "id")
	param.Values = append(param.Values, "123456")

	member := &Member{}

	if err := inflate.NewPathDecoder(param).Decode(member); err != nil {
		panic(err)
	}

	fmt.Printf("%+v", member)

}
Output:

&{ID:123456}
Example (Query)
package main

import (
	"fmt"
	"net/url"

	"github.com/phogolabs/inflate"
)

func main() {
	type User struct {
		ID   string `query:"id"`
		Name string `query:"name"`
	}

	query, err := url.ParseQuery("id=1&name=Jack")
	if err != nil {
		panic(err)
	}

	user := &User{}

	if err := inflate.NewQueryDecoder(query).Decode(user); err != nil {
		panic(err)
	}

	fmt.Printf("%+v", user)

}
Output:

&{ID:1 Name:Jack}
Example (Set)
package main

import (
	"fmt"

	"github.com/phogolabs/inflate"
)

func main() {
	type Order struct {
		ID string `field:"order_id"`
	}

	type OrderItem struct {
		OrderID string `field:"order_id"`
	}

	source := &Order{ID: "0000123"}
	target := &OrderItem{}

	if err := inflate.Set(target, source); err != nil {
		panic(err)
	}

	fmt.Printf("%+v", target)

}
Output:

&{OrderID:0000123}

func NewCookieDecoder

func NewCookieDecoder(cookies []*http.Cookie) *Decoder

NewCookieDecoder creates a cookie decoder

func NewFormDecoder

func NewFormDecoder(query url.Values) *Decoder

NewFormDecoder creates a path decoder

func NewHeaderDecoder

func NewHeaderDecoder(header http.Header) *Decoder

NewHeaderDecoder creates a header decoder

func NewPathDecoder

func NewPathDecoder(r *chi.RouteParams) *Decoder

NewPathDecoder creates a path decoder

func NewQueryDecoder

func NewQueryDecoder(query url.Values) *Decoder

NewQueryDecoder creates a path decoder

func (*Decoder) Decode

func (d *Decoder) Decode(value interface{}) error

Decode decodes the values to given target

type DefaultProvider

type DefaultProvider struct{}

DefaultProvider returns the default for given field

func (*DefaultProvider) Value

func (p *DefaultProvider) Value(ctx *Context) (interface{}, error)

Value returns the default value if specified

type Field

type Field struct {
	Tag   *Tag
	Name  string
	Value reflect.Value
}

Field represents a struct field

func (*Field) Array

func (f *Field) Array() *Array

Array returns the struct as map

func (*Field) IsZero

func (f *Field) IsZero() bool

IsZero return true if it's zero

func (*Field) Map

func (f *Field) Map() *Map

Map return the struct as map

func (*Field) Struct

func (f *Field) Struct() *Struct

Struct returns the field if it's struct

type HeaderProvider

type HeaderProvider struct {
	Header http.Header
}

HeaderProvider represents a parameter provider that fetches values from incoming request's header

func (*HeaderProvider) Value

func (p *HeaderProvider) Value(ctx *Context) (interface{}, error)

Value returns a primitive value

type Map

type Map struct {
	TagName string
	Key     reflect.Type
	Elem    reflect.Type
	Value   reflect.Value
}

Map represents a map

func MapOf

func MapOf(tagName string, value reflect.Value) *Map

MapOf returns a map

func (*Map) Get

func (m *Map) Get(key reflect.Value) reflect.Value

Get returns the value for given key

func (*Map) Values

func (m *Map) Values() *Array

Values returns the values as array

type PathProvider

type PathProvider struct {
	Param *chi.RouteParams
}

PathProvider represents a parameter provider that fetches values from incoming request's header

func (*PathProvider) Value

func (p *PathProvider) Value(ctx *Context) (interface{}, error)

Value returns a primitive value

type QueryProvider

type QueryProvider struct {
	Query url.Values
}

QueryProvider represents a parameter provider that fetches values from incoming request's cookies

func (*QueryProvider) Value

func (p *QueryProvider) Value(ctx *Context) (interface{}, error)

Value returns a primitive value

type Struct

type Struct struct {
	TagName string
	Value   reflect.Value
}

Struct works with structs

func StructOf

func StructOf(tagName string, value reflect.Value) *Struct

StructOf returns the struct

func (*Struct) Array

func (s *Struct) Array() *Array

Array return the struct's fields as array

func (*Struct) Fields

func (s *Struct) Fields() []*Field

Fields returns the struct fields

func (*Struct) Map

func (s *Struct) Map() *Map

Map return the struct as map

type Tag

type Tag struct {
	Key     string
	Name    string
	Options []string
}

Tag defines a single struct's string literal tag

func ParseTag

func ParseTag(key, value string) *Tag

ParseTag returns the options

func (*Tag) AddOption

func (tag *Tag) AddOption(opt string)

AddOption adds an option

func (*Tag) HasOption

func (tag *Tag) HasOption(opt string) bool

HasOption returns true if the option is available

type ValueConverter

type ValueConverter interface {
	Convert(source, target interface{}) error
}

ValueConverter converts source to target

type ValueProvider

type ValueProvider interface {
	Value(ctx *Context) (interface{}, error)
}

ValueProvider provides a value

Directories

Path Synopsis
Code generated by counterfeiter.
Code generated by counterfeiter.

Jump to

Keyboard shortcuts

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