-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
117 lines (93 loc) · 2.04 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
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 main
import (
"flag"
"log"
"net"
"net/http"
"os"
"os/user"
"sync"
"time"
)
type mbContext struct {
Printers *printerConnections
Config *config
}
func (ctx *mbContext) Debugln(v ...interface{}) {
if ctx.Config.Debug {
log.Println(v...)
}
}
func (ctx *mbContext) Debugf(fmt string, v ...interface{}) {
if ctx.Config.Debug {
log.Printf(fmt, v...)
}
}
func main() {
var defaultConfig string
usr, err := user.Current()
if err != nil {
defaultConfig = "/etc/makerbotd/config.json"
} else {
defaultConfig = usr.HomeDir + "/.makerbotd/config.json"
}
confPath := flag.String("config", defaultConfig, "the path to the makerbotd config file")
forceListen := flag.Bool("force-listen", false, "force listen on unix socket if it is in use")
flag.Parse()
conf, err := loadConfig(*confPath)
if err != nil {
panic(err)
}
ctx := mbContext{Config: conf}
printers := printerConnections{}
// Set up printer connections
for _, pc := range conf.Printers {
conn := newPrinterConnection(&ctx, pc)
go conn.Connect()
printers = append(printers, conn)
}
ctx.Printers = &printers
router := getRouter(&ctx)
server := http.Server{
Handler: router,
ReadTimeout: 5 * time.Minute,
}
var wg sync.WaitGroup
if conf.ListenSocket {
if *forceListen {
os.Remove(conf.ListenSocketPath)
}
wg.Add(1)
go func() {
sock, err := net.Listen("unix", conf.ListenSocketPath)
if err != nil {
panic(err)
}
defer sock.Close()
defer os.Remove(conf.ListenSocketPath)
log.Printf("HTTP server listening on UNIX domain socket (force=%v): %s", *forceListen, conf.ListenSocketPath)
err = server.Serve(sock)
if err != nil {
panic(err)
}
wg.Done()
}()
}
if conf.ListenTCP {
wg.Add(1)
go func() {
conn, err := net.Listen("tcp", conf.ListenTCPAddress)
if err != nil {
panic(err)
}
defer conn.Close()
log.Printf("HTTP server listening on TCP address: %s", conf.ListenTCPAddress)
err = server.Serve(conn)
if err != nil {
panic(err)
}
wg.Done()
}()
}
wg.Wait()
}