tendermint/config/config.go

122 lines
2.1 KiB
Go
Raw Normal View History

2014-06-06 11:57:22 -07:00
package config
import (
2014-07-01 14:50:24 -07:00
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
//"crypto/rand"
//"encoding/hex"
2014-06-06 11:57:22 -07:00
)
var APP_DIR = os.Getenv("HOME") + "/.tendermint"
/* Global & initialization */
var Config Config_
func init() {
2014-07-01 14:50:24 -07:00
configFile := APP_DIR + "/config.json"
// try to read configuration. if missing, write default
configBytes, err := ioutil.ReadFile(configFile)
if err != nil {
defaultConfig.write(configFile)
fmt.Println("Config file written to config.json. Please edit & run again")
os.Exit(1)
return
}
// try to parse configuration. on error, die
Config = Config_{}
err = json.Unmarshal(configBytes, &Config)
if err != nil {
log.Panicf("Invalid configuration file %s: %v", configFile, err)
}
err = Config.validate()
if err != nil {
log.Panicf("Invalid configuration file %s: %v", configFile, err)
}
2014-06-06 11:57:22 -07:00
}
/* Default configuration */
var defaultConfig = Config_{
2014-07-01 14:50:24 -07:00
Host: "127.0.0.1",
Port: 8770,
Db: DbConfig{
Type: "level",
Dir: APP_DIR + "/data",
},
Twilio: TwilioConfig{},
2014-06-06 11:57:22 -07:00
}
/* Configuration types */
type Config_ struct {
2014-07-01 14:50:24 -07:00
Host string
Port int
Db DbConfig
Twilio TwilioConfig
2014-06-06 11:57:22 -07:00
}
type TwilioConfig struct {
2014-07-01 14:50:24 -07:00
Sid string
Token string
From string
To string
MinInterval int
2014-06-06 11:57:22 -07:00
}
type DbConfig struct {
2014-07-01 14:50:24 -07:00
Type string
Dir string
2014-06-06 11:57:22 -07:00
}
func (cfg *Config_) validate() error {
2014-07-01 14:50:24 -07:00
if cfg.Host == "" {
return errors.New("Host must be set")
}
if cfg.Port == 0 {
return errors.New("Port must be set")
}
if cfg.Db.Type == "" {
return errors.New("Db.Type must be set")
}
return nil
2014-06-06 11:57:22 -07:00
}
func (cfg *Config_) bytes() []byte {
2014-07-01 14:50:24 -07:00
configBytes, err := json.Marshal(cfg)
if err != nil {
panic(err)
}
return configBytes
2014-06-06 11:57:22 -07:00
}
func (cfg *Config_) write(configFile string) {
2014-07-01 14:50:24 -07:00
if strings.Index(configFile, "/") != -1 {
err := os.MkdirAll(filepath.Dir(configFile), 0700)
if err != nil {
panic(err)
}
}
err := ioutil.WriteFile(configFile, cfg.bytes(), 0600)
if err != nil {
panic(err)
}
2014-06-06 11:57:22 -07:00
}
/* TODO: generate priv/pub keys
func generateKeys() string {
bytes := &[30]byte{}
rand.Read(bytes[:])
return hex.EncodeToString(bytes[:])
}
*/