You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.4 KiB

10 years ago
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "errors"
  11. //"crypto/rand"
  12. //"encoding/hex"
  13. )
  14. var APP_DIR = os.Getenv("HOME") + "/.tendermint"
  15. /* Global & initialization */
  16. var Config Config_
  17. func init() {
  18. configFile := APP_DIR+"/config.json"
  19. // try to read configuration. if missing, write default
  20. configBytes, err := ioutil.ReadFile(configFile)
  21. if err != nil {
  22. defaultConfig.write(configFile)
  23. fmt.Println("Config file written to config.json. Please edit & run again")
  24. os.Exit(1)
  25. return
  26. }
  27. // try to parse configuration. on error, die
  28. Config = Config_{}
  29. err = json.Unmarshal(configBytes, &Config)
  30. if err != nil {
  31. log.Panicf("Invalid configuration file %s: %v", configFile, err)
  32. }
  33. err = Config.validate()
  34. if err != nil {
  35. log.Panicf("Invalid configuration file %s: %v", configFile, err)
  36. }
  37. }
  38. /* Default configuration */
  39. var defaultConfig = Config_{
  40. Host: "127.0.0.1",
  41. Port: 8770,
  42. Db: DbConfig{
  43. Type: "level",
  44. Dir: APP_DIR+"/data",
  45. },
  46. Twilio: TwilioConfig{
  47. },
  48. }
  49. /* Configuration types */
  50. type Config_ struct {
  51. Host string
  52. Port int
  53. Db DbConfig
  54. Twilio TwilioConfig
  55. }
  56. type TwilioConfig struct {
  57. Sid string
  58. Token string
  59. From string
  60. To string
  61. MinInterval int
  62. }
  63. type DbConfig struct {
  64. Type string
  65. Dir string
  66. }
  67. func (cfg *Config_) validate() error {
  68. if cfg.Host == "" { return errors.New("Host must be set") }
  69. if cfg.Port == 0 { return errors.New("Port must be set") }
  70. if cfg.Db.Type == "" { return errors.New("Db.Type must be set") }
  71. return nil
  72. }
  73. func (cfg *Config_) bytes() []byte {
  74. configBytes, err := json.Marshal(cfg)
  75. if err != nil { panic(err) }
  76. return configBytes
  77. }
  78. func (cfg *Config_) write(configFile string) {
  79. if strings.Index(configFile, "/") != -1 {
  80. err := os.MkdirAll(filepath.Dir(configFile), 0700)
  81. if err != nil { panic(err) }
  82. }
  83. err := ioutil.WriteFile(configFile, cfg.bytes(), 0600)
  84. if err != nil {
  85. panic(err)
  86. }
  87. }
  88. /* TODO: generate priv/pub keys
  89. func generateKeys() string {
  90. bytes := &[30]byte{}
  91. rand.Read(bytes[:])
  92. return hex.EncodeToString(bytes[:])
  93. }
  94. */