-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
77 lines (66 loc) · 1.59 KB
/
main.go
File metadata and controls
77 lines (66 loc) · 1.59 KB
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 (
"context"
"eiproxy/client"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strings"
"syscall"
)
var (
mode = flag.String("mode", "server", "Mode to run in (client or server)")
configPath = flag.String("config", "", "Path to config file. By default uses mode name + .json")
)
func main() {
flag.Parse()
if *configPath == "" {
*configPath = *mode + ".json"
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
var err error
if *mode == "client" {
cfg := client.DefaultConfig
readConfig(*configPath, &cfg)
err = client.New(cfg).Run(ctx)
} else if *mode == "server" {
log.Fatalf("Will be available soon")
} else {
log.Fatalf("Unknown mode %q", *mode)
}
if err != nil && !errors.Is(err, context.Canceled) {
message := "Error:\n"
for _, e := range strings.Split(err.Error(), "\n") {
message += fmt.Sprintf(" - %s", e)
}
log.Println(message)
os.Exit(1)
}
}
func readConfig(path string, cfg any) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.Printf("Config file not found, saving default config to %s", path)
data, err = json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Fatalf("Failed to marshal default config: %v", err)
}
err = os.WriteFile(path, data, 0644)
if err != nil {
log.Fatalf("Failed to write default config: %v", err)
}
return
}
log.Fatalf("Failed to read config: %v", err)
}
err = json.Unmarshal(data, cfg)
if err != nil {
log.Fatalf("Failed to parse config: %v", err)
}
}