gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/config.v2/handler.go (about)

     1  package config
     2  
     3  import "reflect"
     4  
     5  type PostHandler interface {
     6  	PostHandle() error
     7  }
     8  
     9  func postHandleStruct(v reflect.Value) error {
    10  	t := v.Type()
    11  	l := t.NumField()
    12  	for i := 0; i < l; i++ {
    13  		f := t.Field(i)
    14  		if f.IsExported() {
    15  			if err := postHandle(v.Field(i)); err != nil {
    16  				return err
    17  			}
    18  		}
    19  	}
    20  	return nil
    21  }
    22  
    23  func postHandleList(v reflect.Value) error {
    24  	if v.IsNil() {
    25  		return nil
    26  	}
    27  	l := v.Len()
    28  	for i := 0; i < l; i++ {
    29  		if err := postHandle(v.Index(i)); err != nil {
    30  			return err
    31  		}
    32  	}
    33  	return nil
    34  }
    35  
    36  func postHandleMap(v reflect.Value) error {
    37  	if v.IsNil() {
    38  		return nil
    39  	}
    40  	iter := v.MapRange()
    41  	for iter.Next() {
    42  		if err := postHandle(iter.Key()); err != nil {
    43  			return err
    44  		}
    45  		if err := postHandle(iter.Value()); err != nil {
    46  			return err
    47  		}
    48  	}
    49  	return nil
    50  }
    51  
    52  func postHandle(v reflect.Value) error {
    53  	for v.Kind() == reflect.Ptr {
    54  		if v.IsNil() {
    55  			return nil
    56  		}
    57  		v = v.Elem()
    58  	}
    59  
    60  	if v.CanAddr() {
    61  		i := v.Addr().Interface()
    62  		if h, ok := i.(PostHandler); ok {
    63  			if err := h.PostHandle(); err != nil {
    64  				return err
    65  			}
    66  			return nil
    67  		}
    68  	}
    69  
    70  	switch v.Kind() {
    71  	case reflect.Struct:
    72  		return postHandleStruct(v)
    73  	case reflect.Slice, reflect.Array:
    74  		return postHandleList(v)
    75  	case reflect.Map:
    76  		return postHandleMap(v)
    77  	default:
    78  		return nil
    79  	}
    80  }
    81  
    82  func PostHandle(c any) error {
    83  	v := reflect.ValueOf(c)
    84  	if v.IsValid() {
    85  		return postHandle(v)
    86  	}
    87  	return nil
    88  }