-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.go
66 lines (56 loc) · 1.31 KB
/
daemon.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
package daemon
import (
"net"
"net/http"
"github.com/leanovate/microtools/logging"
"github.com/leanovate/microtools/rest"
"github.com/leanovate/microtools/routing"
"github.com/untoldwind/trustless/secrets"
)
// Daemon is the daomnized trustless server
type Daemon struct {
logger logging.Logger
secrets secrets.Secrets
listener net.Listener
}
// NewDaemon creates a new trustless daeom
func NewDaemon(secrets secrets.Secrets, logger logging.Logger) *Daemon {
return &Daemon{
logger: logger.WithField("package", "daemon"),
secrets: secrets,
}
}
// Start the daemon
func (d *Daemon) Start() error {
server := &http.Server{
Handler: routing.NewLoggingHandler(
d.routeHandler(),
d.logger.WithContext(map[string]interface{}{"type": "access"}),
),
}
var err error
d.listener, err = d.createListener()
if err != nil {
return err
}
go func() {
d.logger.Infof("Starting daemon: %v", d.listener.Addr())
if err := server.Serve(d.listener); err != nil {
d.logger.ErrorErr(err)
}
}()
return nil
}
// Stop the daemon
func (d *Daemon) Stop() error {
d.logger.Info("Stopping daemon")
if d.listener != nil {
return d.listener.Close()
}
return nil
}
func (d *Daemon) routeHandler() http.Handler {
return routing.NewRouteHandler(
rest.ResourceMatcher(NewRootResource(d.secrets, d.logger)),
)
}