refl

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2021 License: MIT Imports: 5 Imported by: 23

README

Go reflection helpers

Build Status Coverage Status GoDevDoc Code lines Comments

This library provides helper functions to work with structures and field tags.

Documentation

Overview

Package refl provides reflection helpers.

Index

Examples

Constants

View Source
const (
	ErrNeedPointer          = SentinelError("could not find field value in struct")
	ErrMissingFieldValue    = SentinelError("can not take address of structure, please pass a pointer")
	ErrMissingStructOrField = SentinelError("structPtr and fieldPtr are required")
)

Sentinel errors.

Variables

This section is empty.

Functions

func As added in v0.1.4

func As(v interface{}, target interface{}) bool

As unwraps interface value to find value assignable to target.

Example
package main

import (
	"encoding/json"
	"fmt"

	"github.com/swaggest/refl"
)

func main() {
	var (
		v  interface{}
		vv json.Marshaler
	)

	vv = json.RawMessage(`{"abc":123}`)
	v = vv

	target := new(json.RawMessage)
	fmt.Println(refl.As(v, target), string(*target))

}
Output:

true {"abc":123}

func DeepIndirect

func DeepIndirect(t reflect.Type) reflect.Type

DeepIndirect returns first encountered non-pointer type.

func FindEmbeddedSliceOrMap

func FindEmbeddedSliceOrMap(i interface{}) reflect.Type

FindEmbeddedSliceOrMap checks if variable has a slice/array/map or a pointer to it embedded.

func FindTaggedName

func FindTaggedName(structPtr, fieldPtr interface{}, tagName string) (string, error)

FindTaggedName returns tagged name of an entity field.

Entity field is defined by pointer to owner structure and pointer to field in that structure.

entity := MyEntity{}
name, found := sm.FindTaggedName(&entity, &entity.UpdatedAt, "db")

func HasTaggedFields

func HasTaggedFields(i interface{}, tagName string) bool

HasTaggedFields checks if the structure has fields with tag name.

func IsSliceOrMap

func IsSliceOrMap(i interface{}) bool

IsSliceOrMap checks if variable is a slice/array/map or a pointer to it.

func IsStruct

func IsStruct(i interface{}) bool

IsStruct checks if variable is a struct or a pointer to a struct.

func IsZero

func IsZero(v reflect.Value) bool

IsZero reports whether v is the zero value for its type. It panics if the argument is invalid.

Adapted from go1.13 reflect.IsZero.

func JoinErrors

func JoinErrors(errs ...error) error

JoinErrors joins non-nil errors.

func PopulateFieldsFromTags

func PopulateFieldsFromTags(structPtr interface{}, fieldTag reflect.StructTag) error

PopulateFieldsFromTags extracts values from field tag and puts them in according property of structPtr.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"reflect"

	"github.com/swaggest/refl"
)

func main() {
	type schema struct {
		Title      string
		Desc       *string
		Min        *float64
		Max        float64
		Limit      int64
		Offset     *int64
		Deprecated bool
		Required   *bool
	}

	type value struct {
		Property string `title:"Value" desc:"..." min:"-1.23" max:"10.1" limit:"5" offset:"2" deprecated:"true" required:"f"`
	}

	s := schema{}
	tag := reflect.TypeOf(value{}).Field(0).Tag

	err := refl.PopulateFieldsFromTags(&s, tag)
	if err != nil {
		log.Fatal(err)
	}

	j, err := json.Marshal(s)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(j))

}
Output:

{"Title":"Value","Desc":"...","Min":-1.23,"Max":10.1,"Limit":5,"Offset":2,"Deprecated":true,"Required":false}

func ReadBoolPtrTag

func ReadBoolPtrTag(tag reflect.StructTag, name string, holder **bool) error

ReadBoolPtrTag reads bool value from field tag into a pointer.

func ReadBoolTag

func ReadBoolTag(tag reflect.StructTag, name string, holder *bool) error

ReadBoolTag reads bool value from field tag into a value.

func ReadFloatPtrTag

func ReadFloatPtrTag(tag reflect.StructTag, name string, holder **float64) error

ReadFloatPtrTag reads float64 value from field tag into a pointer.

func ReadFloatTag

func ReadFloatTag(tag reflect.StructTag, name string, holder *float64) error

ReadFloatTag reads float64 value from field tag into a value.

func ReadIntPtrTag

func ReadIntPtrTag(tag reflect.StructTag, name string, holder **int64) error

ReadIntPtrTag reads int64 value from field tag into a pointer.

func ReadIntTag

func ReadIntTag(tag reflect.StructTag, name string, holder *int64) error

ReadIntTag reads int64 value from field tag into a value.

func ReadStringPtrTag

func ReadStringPtrTag(tag reflect.StructTag, name string, holder **string)

ReadStringPtrTag reads string value from field tag into a pointer.

func ReadStringTag

func ReadStringTag(tag reflect.StructTag, name string, holder *string)

ReadStringTag reads string value from field tag into a value.

func Tagged

func Tagged(structPtr, fieldPtr interface{}, tagName string) string

Tagged will try to find tagged name and panic on error.

func WalkTaggedFields

func WalkTaggedFields(v reflect.Value, f WalkTaggedFieldFn, tagName string)

WalkTaggedFields iterates top level fields of structure including anonymous embedded fields.

Types

type SentinelError added in v0.1.4

type SentinelError string

SentinelError is a constant error.

func (SentinelError) Error added in v0.1.4

func (se SentinelError) Error() string

Error implements error.

type TypeString

type TypeString string

TypeString is a type name with import path.

func GoType

func GoType(t reflect.Type) TypeString

GoType returns string representation of type name including import path.

Example
package main

import (
	"fmt"
	"reflect"

	"github.com/swaggest/refl"
	fancypath "github.com/swaggest/refl/internal/Fancy-Path"
	"github.com/swaggest/refl/internal/sample"
)

func main() {
	fmt.Println(refl.GoType(reflect.TypeOf(new(fancypath.Sample))))
	fmt.Println(refl.GoType(reflect.TypeOf(new(sample.TestSampleStruct))))

}
Output:

*github.com/swaggest/refl/internal/Fancy-Path::fancypath.Sample
*github.com/swaggest/refl/internal/sample.TestSampleStruct

type WalkTaggedFieldFn

type WalkTaggedFieldFn func(v reflect.Value, sf reflect.StructField, tag string)

WalkTaggedFieldFn defines callback.

Directories

Path Synopsis
internal
Fancy-Path
Package fancypath contains test data.
Package fancypath contains test data.
sample
Package sample contains test data.
Package sample contains test data.

Jump to

Keyboard shortcuts

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