github.com/profzone/eden-framework@v1.0.10/pkg/strings/marshallers.go (about)

     1  package str
     2  
     3  import (
     4  	"encoding/json"
     5  	"reflect"
     6  	"time"
     7  
     8  	"github.com/profzone/eden-framework/pkg/reflectx"
     9  )
    10  
    11  var StdStringifier = Stringifier{}
    12  
    13  func init() {
    14  	StdStringifier.Register(UnmarshalJSONUnmarshaler, UnmarshalTimeDuration)
    15  }
    16  
    17  func UnmarshalTimeDuration(s string, v reflect.Value) (matched bool, err error) {
    18  	tpe := reflectx.IndirectType(v.Type())
    19  	if tpe.PkgPath() == "time" && tpe.Name() == "Duration" {
    20  		matched = true
    21  		d, errForParse := time.ParseDuration(s)
    22  		if errForParse != nil {
    23  			err = errForParse
    24  			return
    25  		}
    26  		v.SetInt(int64(d))
    27  	}
    28  	return
    29  }
    30  
    31  func UnmarshalJSONUnmarshaler(s string, rv reflect.Value) (matched bool, err error) {
    32  	if rv.CanAddr() {
    33  		rv = rv.Addr()
    34  	}
    35  	if unmarshaler, ok := rv.Interface().(json.Unmarshaler); ok {
    36  		matched = true
    37  		tpe := rv.Type()
    38  		errForUnmarshal := unmarshaler.UnmarshalJSON([]byte(s))
    39  		if errForUnmarshal != nil || !reflect.TypeOf(unmarshaler).Elem().ConvertibleTo(tpe) {
    40  			err = errForUnmarshal
    41  			return
    42  		}
    43  		rv.Set(reflect.ValueOf(unmarshaler).Elem().Convert(tpe))
    44  	}
    45  	return
    46  }