github.com/songzhibin97/gkit@v1.2.13/coding/yaml/yaml.go (about)

     1  package yaml
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/songzhibin97/gkit/coding"
     7  	"gopkg.in/yaml.v2"
     8  )
     9  
    10  const Name = "yaml"
    11  
    12  func init() {
    13  	_ = coding.RegisterCode(code{})
    14  }
    15  
    16  type code struct{}
    17  
    18  func (c code) Marshal(v interface{}) ([]byte, error) {
    19  	return yaml.Marshal(v)
    20  }
    21  
    22  func (c code) Unmarshal(data []byte, v interface{}) error {
    23  	rv := reflect.ValueOf(v)
    24  	for rv.Kind() == reflect.Ptr {
    25  		if rv.IsNil() {
    26  			rv.Set(reflect.New(rv.Type().Elem()))
    27  		}
    28  		rv = rv.Elem()
    29  	}
    30  	return yaml.Unmarshal(data, v)
    31  }
    32  
    33  func (c code) Name() string {
    34  	return Name
    35  }