github.com/songzhibin97/gkit@v1.2.13/tools/vto/default.go (about)

     1  package vto
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/songzhibin97/gkit/tools"
     7  )
     8  
     9  func CompletionDefault(dst interface{}) error {
    10  	dstT := reflect.TypeOf(dst)
    11  	if dstT.Kind() != reflect.Ptr {
    12  		return tools.ErrorMustPtr
    13  	}
    14  
    15  	dstT = dstT.Elem()
    16  	if dstT.Kind() != reflect.Struct {
    17  		return tools.ErrorMustStructPtr
    18  	}
    19  
    20  	dstV := reflect.ValueOf(dst).Elem()
    21  	for i := 0; i < dstT.NumField(); i++ {
    22  		field := dstT.Field(i)
    23  		if !field.IsExported() {
    24  			continue
    25  		}
    26  		d := dstV.Field(i)
    27  
    28  		if d.Kind() == reflect.Struct {
    29  			err := CompletionDefault(d.Addr().Interface())
    30  			if err != nil {
    31  				return err
    32  			}
    33  			continue
    34  		}
    35  
    36  		defaultTag := field.Tag.Get("default")
    37  		if defaultTag == "" {
    38  			continue
    39  		}
    40  
    41  		if d.IsZero() {
    42  			if d.Kind() == reflect.Ptr {
    43  				ss := reflect.New(d.Type().Elem())
    44  				err := bindDefault(ss.Elem(), defaultTag, field)
    45  				if err != nil {
    46  					return err
    47  				}
    48  				d.Set(ss)
    49  			} else {
    50  				err := bindDefault(d, defaultTag, field)
    51  				if err != nil {
    52  					return err
    53  				}
    54  			}
    55  		}
    56  	}
    57  
    58  	return nil
    59  }