-
Notifications
You must be signed in to change notification settings - Fork 43
/
config.go
96 lines (83 loc) · 2.32 KB
/
config.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/user"
)
// DefaultP2PPort is the default TCP port for p2p connections
const DefaultP2PPort = 2017
// DefaultBlockWebServerPort is the default TCP port for the HTTP server
const DefaultBlockWebServerPort = 2018
// DefaultConfigFile is the default configuration filename
const DefaultConfigFile = "/etc/daisy/config.json"
// DefaultDataDir is the default data directory
const DefaultDataDir = ".daisy"
var cfg struct {
configFile string
P2pPort int `json:"p2p_port"`
DataDir string `json:"data_dir"`
httpPort int `json:"http_port"`
showHelp bool
faster bool
p2pBlockInline bool
}
// Initialises defaults, parses command line
func configInit() {
u, err := user.Current()
if err != nil {
log.Panicln(err)
}
cfg.DataDir = fmt.Sprintf("%s/%s", u.HomeDir, DefaultDataDir)
// Init defaults
cfg.P2pPort = DefaultP2PPort
cfg.httpPort = DefaultBlockWebServerPort
// Config file is parsed first
for i, arg := range os.Args {
if arg == "-conf" || arg == "--conf" {
if i+1 >= len(os.Args) {
log.Fatal("-conf requires filename argument")
}
cfg.configFile = os.Args[i+1]
}
}
if cfg.configFile != "" {
loadConfigFile()
}
// Then override the configuration with command-line flags
flag.IntVar(&cfg.P2pPort, "port", cfg.P2pPort, "P2P port")
flag.IntVar(&cfg.httpPort, "http-port", cfg.httpPort, "HTTP port")
flag.StringVar(&cfg.DataDir, "dir", cfg.DataDir, "Data directory")
flag.BoolVar(&cfg.showHelp, "help", false, "Shows CLI usage information")
flag.BoolVar(&cfg.faster, "faster", false, "Be faster when starting up")
flag.BoolVar(&cfg.p2pBlockInline, "p2pblockinline", false, "Send blocks to peers inline instead of over HTTP")
flag.Parse()
if cfg.showHelp {
actionHelp()
os.Exit(0)
}
if _, err := os.Stat(cfg.DataDir); err != nil {
log.Println("Data directory", cfg.DataDir, "doesn't exist, creating.")
err = os.Mkdir(cfg.DataDir, 0700)
if err != nil {
log.Panicln(err)
}
}
if cfg.P2pPort < 1 || cfg.P2pPort > 65535 {
log.Fatal("Invalid TCP port", cfg.P2pPort)
}
}
// Loads the JSON config file.
func loadConfigFile() {
data, err := ioutil.ReadFile(cfg.configFile)
if err != nil {
log.Fatal(err)
}
err = json.Unmarshal(data, &cfg)
if err != nil {
log.Fatal(err)
}
}