github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zpool/inject.go (about)

     1  package zpool
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/sohaha/zlsgo/zdi"
     7  )
     8  
     9  type (
    10  	invokerPre func() error
    11  )
    12  
    13  func (i invokerPre) Invoke(_ []interface{}) ([]reflect.Value, error) {
    14  	return nil, i()
    15  }
    16  
    17  var (
    18  	_ zdi.PreInvoker = (*invokerPre)(nil)
    19  )
    20  
    21  func invokeHandler(v []reflect.Value, err error) error {
    22  	if err != nil {
    23  		return err
    24  	}
    25  	for i := range v {
    26  		val := v[i].Interface()
    27  		switch e := val.(type) {
    28  		case error:
    29  			return e
    30  		}
    31  	}
    32  	return nil
    33  }
    34  
    35  func (wp *WorkPool) Injector() zdi.TypeMapper {
    36  	return wp.injector
    37  }
    38  
    39  func (wp *WorkPool) handlerFunc(h Task) (fn taskfn) {
    40  	switch v := h.(type) {
    41  	case func():
    42  		return func() error {
    43  			v()
    44  			return nil
    45  		}
    46  	case func() error:
    47  		return func() error {
    48  			return invokeHandler(wp.injector.Invoke(invokerPre(v)))
    49  		}
    50  	case zdi.PreInvoker:
    51  		return func() error {
    52  			err := invokeHandler(wp.injector.Invoke(v))
    53  			return err
    54  		}
    55  	default:
    56  		return func() error {
    57  			return invokeHandler(wp.injector.Invoke(v))
    58  		}
    59  	}
    60  }