-
Notifications
You must be signed in to change notification settings - Fork 9
/
actions.go
108 lines (100 loc) · 2.43 KB
/
actions.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package daemonigo
import (
"fmt"
"os"
)
// Daemon default actions.
// Can be changed with SetAction() and RemoveAction() functions.
var actions = map[string]func(){
"start": func() {
switch isRunning, _, err := Status(); {
case err != nil:
printStatusErr(err)
case isRunning:
fmt.Println(AppName + " is already started and running now")
default:
start()
}
},
"stop": func() {
switch isRunning, process, err := Status(); {
case err != nil:
printStatusErr(err)
case !isRunning:
fmt.Println(AppName + " is NOT running or already stopped")
default:
stop(process)
}
},
"status": func() {
switch isRunning, process, err := Status(); {
case err != nil:
printStatusErr(err)
case !isRunning:
fmt.Println(AppName + " is NOT running")
default:
fmt.Printf("%s is running with PID %d\n", AppName, process.Pid)
}
},
"restart": func() {
isRunning, process, err := Status()
if err != nil {
printStatusErr(err)
return
}
if isRunning {
stop(process)
}
start()
},
}
// Helper function to print errors of Status() function.
func printStatusErr(e error) {
fmt.Println("Checking status of " + AppName + " failed")
fmt.Println("Details:", e.Error())
}
// Helper function to operate with errors printing in actions.
func failed(e error) {
fmt.Println("FAILED")
fmt.Println("Details:", e.Error())
}
// Helper function which wraps Stop() with printing
// for using in daemon default actions.
func stop(process *os.Process) {
fmt.Printf("Stopping %s...", AppName)
if err := Stop(process); err != nil {
failed(err)
} else {
fmt.Println("OK")
}
}
// Helper function which wraps Start() with printing
// for using in daemon default actions.
func start() {
fmt.Printf("Starting %s...", AppName)
if err := Start(1); err != nil {
failed(err)
} else {
fmt.Println("OK")
}
}
// Sets new daemon action with given name or overrides previous.
//
// This function is not concurrent safe, so you must synchronize
// its calls in case of usage in multiple goroutines.
func SetAction(name string, action func()) {
if name == "" {
panic("daemonigo.SetAction(): name cannot be empty")
}
if action == nil {
panic("daemonigo.SetAction(): action cannot be nil")
}
actions[name] = action
}
// Removes daemon action with given name.
//
// This function is not concurrent safe, so you must synchronize
// its calls in case of usage in multiple goroutines.
func RemoveAction(name string) {
delete(actions, name)
}