-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.go
102 lines (87 loc) · 1.69 KB
/
lib.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
package simple_daemon
import (
"github.com/kardianos/service"
"log"
"os"
"path"
"strings"
)
type Info struct {
Name string
Description string
Dependencies []string
}
type Behavior struct {
WorkFn func() error
ExitFn func() error
UseExeDirAsCwd bool
}
type program struct {
B Behavior
}
func (p *program) Start(s service.Service) error {
go p.run()
return nil
}
func (p *program) run() {
if p.B.UseExeDirAsCwd {
if err := SetCwdAsBinaryDirectory(); err != nil {
panic(err)
}
}
if err := p.B.WorkFn(); err != nil {
panic(err)
}
}
func (p *program) Stop(s service.Service) error {
if p.B.ExitFn != nil {
if err := p.B.ExitFn(); err != nil {
return err
}
}
return nil
}
func Start(info Info, behavior Behavior) error {
svcConfig := &service.Config{
Name: info.Name,
DisplayName: info.Name,
Description: info.Description,
Arguments: nil,
}
if len(os.Args) > 2 && os.Args[1] == "install" {
svcConfig.Arguments = os.Args[2:]
}
prg := &program{
B: behavior,
}
s, err := service.New(prg, svcConfig)
if err != nil {
log.Fatal(err)
}
if len(os.Args) > 1 {
if os.Args[1] == "install" {
return s.Install()
} else if os.Args[1] == "uninstall" {
return s.Uninstall()
} else if os.Args[1] == "start" {
return s.Start()
} else if os.Args[1] == "stop" {
return s.Stop()
} else if os.Args[1] == "status" {
status, err := s.Status()
if err != nil {
log.Fatal(err)
}
log.Println(status)
return nil
}
}
// TODO: improve loggers
if err = s.Run(); err != nil {
return err
}
return nil
}
func SetCwdAsBinaryDirectory() error {
return os.Chdir(path.Dir(strings.ReplaceAll(os.Args[0], "\\", "/")))
}