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

     1  //go:build !go1.18
     2  // +build !go1.18
     3  
     4  package zutil
     5  
     6  import (
     7  	"sync"
     8  	"time"
     9  )
    10  
    11  // Once initialize the singleton
    12  func Once(fn func() interface{}) func() interface{} {
    13  	var (
    14  		once sync.Once
    15  		ivar interface{}
    16  	)
    17  	return func() interface{} {
    18  		once.Do(func() {
    19  			err := TryCatch(func() error {
    20  				ivar = fn()
    21  				return nil
    22  			})
    23  			if err != nil {
    24  				go func() {
    25  					time.Sleep(time.Second)
    26  					once = sync.Once{}
    27  				}()
    28  			}
    29  		})
    30  		return ivar
    31  	}
    32  }