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

     1  package courier
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	"github.com/profzone/eden-framework/pkg/courier/status_error"
     8  )
     9  
    10  type TUnmarshal func(data []byte, v interface{}) error
    11  
    12  type Result struct {
    13  	Err       error
    14  	Meta      Metadata
    15  	Data      []byte
    16  	Unmarshal TUnmarshal
    17  }
    18  
    19  func (r Result) BindMeta(meta Metadata) *Result {
    20  	for key, values := range r.Meta {
    21  		meta.Set(key, values...)
    22  	}
    23  	return &r
    24  }
    25  
    26  func (r Result) Into(v interface{}) error {
    27  	if r.Err != nil {
    28  		return r.Err
    29  	}
    30  	if r.Unmarshal == nil {
    31  		r.Unmarshal = UnmarshalBytes
    32  	}
    33  	if len(r.Data) > 0 {
    34  		err := r.Unmarshal(r.Data, v)
    35  		if err != nil {
    36  			return status_error.InvalidStruct.StatusError().WithDesc(err.Error())
    37  		}
    38  	}
    39  	return nil
    40  }
    41  
    42  func UnmarshalBytes(data []byte, v interface{}) error {
    43  	if _, ok := v.(*[]byte); ok {
    44  		reflect.Indirect(reflect.ValueOf(v)).SetBytes(data)
    45  		return nil
    46  	}
    47  	return fmt.Errorf("target value %#v is not []byte, data: %v", v, data)
    48  }