This repository has been archived by the owner on Jul 18, 2020. It is now read-only.
/
service.go
117 lines (93 loc) · 2.06 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package service
import (
"flag"
"fmt"
"os"
"strings"
"github.com/kardianos/service"
"github.com/caddyserver/caddy"
)
var (
name, action string
instance *caddy.Instance
)
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
instance, err = caddy.Start(caddyfile)
if err != nil {
return err
}
return nil
}
func (p *program) Stop(s service.Service) error {
instance.ShutdownCallbacks()
err := instance.Stop()
instance = nil
return err
}
func hook(event caddy.EventName, info interface{}) error {
if event != caddy.StartupEvent {
return nil
}
config := &service.Config{
Name: strings.ToLower(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 {
exit(err)
}
if action != "" {
exit(actionHandler(action, s))
}
exit(s.Run())
return nil
}
func exit(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
os.Exit(0)
}
func actionHandler(action string, s service.Service) error {
if action != "status" {
return service.Control(s, action)
}
code, _ := s.Status()
switch code {
case service.StatusUnknown:
fmt.Println("Caddy service is not installed.")
case service.StatusStopped:
fmt.Println("Caddy service is not running.")
case service.StatusRunning:
fmt.Println("Caddy service is running.")
default:
fmt.Println("Error: ", code)
}
return nil
}