forked from dillonhafer/garage-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (74 loc) · 2.56 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 (
"flag"
"fmt"
"net/http"
"os"
"github.com/dillonhafer/garage-server/door"
)
const Version = "6.0.0"
var options struct {
http string
pinNumber int
statusPinNumber int
sleepTimeout int
cert string
key string
log string
version bool
}
var SharedSecret = os.Getenv("GARAGE_SECRET")
func main() {
if len(os.Args) > 1 && os.Args[1] == "update" {
CheckForUpdates()
os.Exit(0)
}
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s [options]\n", os.Args[0])
flag.PrintDefaults()
}
flag.IntVar(&options.pinNumber, "pin", 25, "GPIO pin of relay")
flag.IntVar(&options.statusPinNumber, "status-pin", 10, "GPIO pin of reed switch")
flag.IntVar(&options.sleepTimeout, "sleep", 100, "Time in milliseconds to keep switch closed")
flag.StringVar(&options.http, "http", "", "HTTP listen address (e.g. 127.0.0.1:8225)")
flag.StringVar(&options.cert, "cert", "", "SSL certificate path (e.g. /ssl/example.com.cert)")
flag.StringVar(&options.key, "key", "", "SSL certificate key (e.g. /ssl/example.com.key)")
flag.StringVar(&options.log, "log", "", "Path to read logs from")
flag.BoolVar(&options.version, "version", false, "print version and exit")
flag.Parse()
if options.version {
fmt.Printf("garage-server v%v\n", Version)
os.Exit(0)
}
if SharedSecret == "" {
println("You did not set GARAGE_SECRET env var")
os.Exit(1)
}
serveAddress := "127.0.0.1:8225"
if options.http != "" {
serveAddress = options.http
}
Relay := CreateRelayHandle(door.ToggleSwitch, apiLogHandler, options.pinNumber, options.sleepTimeout)
Status := CreateDoorStatusHandler(door.CheckDoorStatus, apiLogHandler, options.statusPinNumber)
AppVersion := CreateVersionHandler(apiLogHandler)
Logs := CreateLogsHandler(apiLogHandler, options.log)
http.HandleFunc("/toggle", Relay)
http.HandleFunc("/status", Status)
http.HandleFunc("/version", AppVersion)
http.HandleFunc("/logs", Logs)
fmt.Fprintln(os.Stderr, "=> Booting Garage Server ", Version)
fmt.Fprintln(os.Stderr, "=> Run `garage-server -h` for more startup options")
fmt.Fprintln(os.Stderr, "=> Ctrl-C to shutdown server")
var err error
if options.key != "" && options.cert != "" {
fmt.Fprintln(os.Stderr, fmt.Sprintf("* Listening on https://%s", serveAddress))
err = http.ListenAndServeTLS(serveAddress, options.cert, options.key, nil)
} else {
fmt.Fprintln(os.Stderr, fmt.Sprintf("* Listening on http://%s", serveAddress))
err = http.ListenAndServe(serveAddress, nil)
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}