This repository has been archived by the owner on Jul 18, 2020. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
service.go
93 lines (74 loc) · 1.53 KB
/
service.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
package service
import (
"flag"
"fmt"
"os"
"github.com/kardianos/service"
"github.com/mholt/caddy"
)
var (
logger service.Logger
name, action string
)
func init() {
flag.StringVar(&name, "name", "Caddy", "Caddy's service name")
flag.StringVar(&action, "service", "", "install, uninstall, start, stop, restart")
caddy.RegisterEventHook("service", hook)
}
type program struct{}
func (p *program) Start(s service.Service) error {
// Get Caddyfile input
caddyfile, err := caddy.LoadCaddyfile(flag.Lookup("type").Value.String())
if err != nil {
return err
}
// Start your engines
_, err = caddy.Start(caddyfile)
if err != nil {
return err
}
return nil
}
func (p *program) Stop(s service.Service) error {
return caddy.Stop()
}
func hook(event caddy.EventName) error {
if event != caddy.StartupEvent {
return nil
}
config := &service.Config{
Name: name,
DisplayName: name,
Description: "Caddy's service",
Arguments: []string{},
}
flag.VisitAll(func(f *flag.Flag) {
// ignore our own flags
if f.Name == "service" || f.Name == "name" {
return
}
// ignore flags with default value
if f.Value.String() == f.DefValue {
return
}
config.Arguments = append(config.Arguments, "-"+f.Name, f.Value.String())
})
s, err := service.New(&program{}, config)
if err != nil {
return err
}
if action != "" {
err = service.Control(s, action)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(0)
}
err = s.Run()
if err != nil {
return err
}
os.Exit(0)
return nil
}