github.com/jtzjtz/kit@v1.0.2/conn/conn.go (about) 1 package conn 2 3 import ( 4 "errors" 5 "fmt" 6 ) 7 8 var connNeedClosed []func() = make([]func(), 0) 9 10 //存储需要关闭的conn ,func() 函数内根据各自的规则写关闭代码 11 func PutNewConn(closeFunc func()) { 12 connNeedClosed = append(connNeedClosed, closeFunc) 13 } 14 func CreateNewInit(createFunc func() error, closeFunc func() error) (er error) { 15 retryCount := 0 16 defer func() { 17 if err := recover(); err != nil { 18 er = errors.New("创建初始化失败") 19 } 20 }() 21 retry: 22 er = createFunc() 23 if er != nil { 24 if retryCount < 3 { 25 retryCount++ 26 fmt.Printf("CreateNewInit failed retrycount=%s error:", retryCount, er.Error()) 27 goto retry 28 } else { 29 return er 30 } 31 } 32 if closeFunc != nil { 33 er = closeFunc() 34 } 35 return er 36 37 } 38 39 //关闭所有存储的conn,建议在main函数中调用 defer conn.close() 40 func Close() (er error) { 41 42 defer func() { 43 if err := recover(); err != nil { 44 println("释放conn报错") 45 er = errors.New("释放conn报错") 46 } 47 }() 48 for _, closeFunc := range connNeedClosed { 49 if closeFunc != nil { 50 closeFunc() 51 } 52 } 53 return nil 54 55 }