gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/lifecycle/starter.go (about)

     1  package lifecycle
     2  
     3  type Starter interface {
     4  	DoStart(Lifecycle) (runFn RunFunc, closeFn CloseFunc, err error)
     5  }
     6  
     7  type StarterFunc func(Lifecycle) (runFn RunFunc, closeFn CloseFunc, err error)
     8  
     9  type starterFunc StarterFunc
    10  
    11  func FuncStarter(starterFn StarterFunc) Starter {
    12  	if starterFn == nil {
    13  		starterFn = func(Lifecycle) (runFn RunFunc, closeFn CloseFunc, err error) {
    14  			return nil, nil, nil
    15  		}
    16  	}
    17  	return starterFunc(starterFn)
    18  }
    19  
    20  func (f starterFunc) DoStart(lifecycle Lifecycle) (runFn RunFunc, closeFn CloseFunc, err error) {
    21  	return f(lifecycle)
    22  }
    23  
    24  type starterRunner struct {
    25  	runnerSetter interface{ setRunner(runner Runner) }
    26  	starter      Starter
    27  	runFn        RunFunc
    28  	closeFn      CloseFunc
    29  }
    30  
    31  func newStarterRunner(runnerSetter interface{ setRunner(runner Runner) }, starter Starter) *starterRunner {
    32  	return &starterRunner{
    33  		runnerSetter: runnerSetter,
    34  		starter:      starter,
    35  	}
    36  }
    37  
    38  func (r *starterRunner) Runner() Runner {
    39  	return FuncRunner(r.start, nil, nil)
    40  }
    41  
    42  func (r *starterRunner) RunningRunner() Runner {
    43  	return FuncRunner(nil, r.run, r.closeFn)
    44  }
    45  
    46  func (r *starterRunner) start(lifecycle Lifecycle) error {
    47  	runFn, closeFn, err := r.starter.DoStart(lifecycle)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	r.runFn, r.closeFn = runFn, closeFn
    52  	r.runnerSetter.setRunner(r.RunningRunner())
    53  	return nil
    54  }
    55  
    56  func (r *starterRunner) run(lifecycle Lifecycle) (err error) {
    57  	if r.runFn != nil {
    58  		err = r.runFn(lifecycle)
    59  	}
    60  	r.runnerSetter.setRunner(r.Runner())
    61  	return err
    62  }