-
Notifications
You must be signed in to change notification settings - Fork 6
/
example.go
77 lines (66 loc) · 1.56 KB
/
example.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
package main
import (
"encoding/json"
"log"
"os"
"path"
"sync"
"github.com/RoanBrand/SerialToTCPBridgeProtocol/comwrapper"
)
func main() {
c, err := loadConfig()
if err != nil {
log.Fatalf(`%v (You must have a valid "config.json" next to the executable)`, err)
}
if len(c.Gateways) == 0 {
log.Fatal("No gateways configured in the config. Exiting.")
}
w := sync.WaitGroup{}
for _, v := range c.Gateways {
w.Add(1)
go func(v gatewayConfig) {
com := comwrapper.NewComPortGateway(v.COMPortName, v.COMBaudRate)
com.ListenAndServe()
w.Done()
}(v)
}
w.Wait()
}
// Configuration by json file.
type gatewayConfig struct {
GatewayName string `json:"gateway name"`
COMPortName string `json:"comport name"`
COMBaudRate int `json:"baud rate"`
}
type config struct {
Gateways []gatewayConfig `json:"gateways"`
}
func loadConfig() (*config, error) {
filePath := "config.json"
// if file not found in current WD, try executable's folder
if !fileExists(filePath) {
exePath, err := os.Executable()
if err != nil {
return nil, err
}
filePath = path.Join(path.Dir(exePath), filePath)
}
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
configuration := config{}
err = json.NewDecoder(file).Decode(&configuration)
if err != nil {
return nil, err
}
return &configuration, nil
}
// fileExists checks if a file exists and is not a directory before we try using it to prevent further errors.
func fileExists(filePath string) bool {
info, err := os.Stat(filePath)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}