This repository has been archived by the owner on Nov 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
90 lines (81 loc) · 1.73 KB
/
main.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
package main
import (
"context"
"fmt"
"html"
"net/http"
"os"
"time"
"github.com/nsemikov/go-daemon"
)
type service struct {
server *http.Server
}
func (s service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}
func (s service) Start() error {
// Non-blocking function
go s.server.ListenAndServe()
fmt.Println("started at http://localhost:8080")
return nil
}
func (s service) Stop() error {
// Non-blocking function
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
return s.server.Shutdown(ctx)
}
func configure() *daemon.Config {
s := &service{}
s.server = &http.Server{
Addr: ":8080",
Handler: s,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
cfg := daemon.NewConfig()
cfg.Name = "cmd_example"
cfg.Description = "Command Line daemon example"
cfg.StartHdlr = s.Start
cfg.StopHdlr = s.Stop
cfg.HideMethodsWarning = true
return cfg
}
func main() {
d, _ := daemon.New(configure())
var (
usage = "Usage: " + os.Args[0] + " install | uninstall | restart | start | stop | status"
status string
err error
)
if len(os.Args) > 1 {
command := os.Args[1]
switch command {
case "install":
status, err = d.Install(os.Args[2:]...)
case "uninstall":
status, err = d.Uninstall()
case "restart":
status, err = d.Restart()
case "start":
status, err = d.Start()
case "stop":
status, err = d.Stop()
case "status":
status, err = d.Status()
default:
err = fmt.Errorf(usage)
}
} else {
err = d.Run()
}
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
if status != "" {
fmt.Println(status)
}
}