github.com/kick-project/maker@v1.1.1-0.20211031110251-7b74922fa493/internal/resources/exit/exit.go (about) 1 // Package exit handles exit to OS 2 package exit 3 4 import ( 5 "fmt" 6 "os" 7 ) 8 9 const ( 10 // MNone set the exit mode at default. When Exit.Exit is called it exits 11 // with the as normal with the supplied return code. 12 MNone = iota 13 // MPanic set the exit mode to panic. When Exit.Exit is called then a panic 14 // will ensue instead of exiting. 15 MPanic 16 ) 17 18 var ( 19 // ExitMode is the current exit mode. Should be one of MNone or MPanic 20 ExitMode int 21 ) 22 23 // Handler exit handling 24 type Handler struct { 25 Mode int `validate:"gte=0|lte=1"` 26 } 27 28 // Exit exit function with exit code. 0 is success 29 func (e *Handler) Exit(code int) { 30 switch e.Mode { 31 case MNone: 32 os.Exit(code) 33 case MPanic: 34 panic(fmt.Sprintf("Exit %d\n", code)) 35 default: 36 panic(fmt.Sprintf("Unknown exit mode: %d", e.Mode)) 37 } 38 } 39 40 // Exit exit function with exit code. 0 is success 41 func Exit(code int) { 42 h := Handler{ 43 Mode: ExitMode, 44 } 45 h.Exit(code) 46 } 47 48 // Mode sets the exit mode for the exit.Exit call. Current modes are, 49 // exit.None (default - call exit mode directly) & exit.Panic (panic instead of exiting) 50 // Returns true if exit mode was was successfully set. 51 func Mode(mode int) (ok bool) { 52 switch mode { 53 case MNone: 54 ExitMode = MNone 55 ok = true 56 case MPanic: 57 ExitMode = MPanic 58 ok = true 59 default: 60 panic(fmt.Sprintf("Unknown exit mode: %d", mode)) 61 } 62 return 63 }