Exemplo n.º 1
0
func (cp *ConfigPlugin) ProcessCommand(cmd *IRCCommand) {
	var err error
	switch cmd.Command {
	case "version":
		cp.ic.Reply(cmd, cp.ic.GetStringOption("Info", "version"))
	case "source":
		cp.ic.Reply(cmd, cp.ic.GetStringOption("Info", "source"))
	case "writeconfig":
		cp.Lock()
		err = cp.Conf.WriteFile(cp.filename, 0644, "IRC Bot Config")
		if err != nil {
			cp.ic.Reply(cmd, "Error writing config: "+err.Error())
		}
		cp.Conf, err = config.ReadDefault(cp.filename)
		if err != nil {
			cp.ic.Reply(cmd, "Error loading config: "+err.Error())
		}
		cp.Unlock()
		cp.ic.Reply(cmd, "Successfully flushed cached config entries")
	case "loadconfig":
		cp.Lock()
		cp.Conf, err = config.ReadDefault(cp.filename)
		if err != nil {
			cp.ic.Reply(cmd, "Error loading config: "+err.Error())
		}
		cp.Unlock()
		cp.ic.Reply(cmd, "Successfully loaded config entries")
	}
}
Exemplo n.º 2
0
func NewConfigPlugin(filename string) *ConfigPlugin {
	c, ok := config.ReadDefault(filename)
	if ok != nil {
		c = config.NewDefault()
		c.AddSection("Server")
		c.AddOption("Server", "host", "dpaulus.dyndns.org:6667")
		c.AddOption("Server", "nick", "testbot")
		c.AddOption("Server", "ident", "ident")
		c.AddOption("Server", "realname", "TestBot Client")
		c.AddOption("Server", "trigger", ".")
		c.AddSection("Auth")
		c.AddSection("Info")
		c.WriteFile(filename, 0644, "IRC Bot default config file")
		log.Println("Note: A new default configuration file has been generated in " + filename + ". Please edit it to suit your needs and restart the bot then")
		os.Exit(1)
	}
	for _, x := range []string{"host", "nick", "ident", "realname"} {
		_, err := c.String("Server", x)
		if err != nil {
			log.Fatal("Error while parsing config: " + err.Error())
		}
	}
	trigger, err := c.String("Server", "trigger")
	if err != nil {
		log.Fatal(err)
	}
	if utf8.RuneCountInString(trigger) != 1 {
		log.Fatal("Trigger must be exactly one unicode rune long")
	}
	return &ConfigPlugin{filename: filename, Conf: c}
}
Exemplo n.º 3
0
func ReadIniFile(inifile string) error {
	conf, err := config.ReadDefault(inifile)
	if err != nil {
		return fmt.Errorf("Read %v error. %v", inifile, err.Error())
	}

	Addr, _ = conf.String("service", "addr")
	NumCpu, _ = conf.Int("service", "num_cpu")
	AcceptTimeout, _ = conf.Int("service", "accept_timeout")
	ReadTimeout, _ = conf.Int("service", "read_timeout")
	WriteTimeout, _ = conf.Int("service", "write_timeout")

	UuidDB, _ = conf.String("data", "uuid_db")
	OfflineMsgidsDB, _ = conf.String("data", "offline_msgids_db")
	IdToMsgDB, _ = conf.String("data", "id_to_msg_db")
	TimedUpdateDB, _ = conf.Int("data", "timed_update_db")

	LogFile, _ = conf.String("debug", "logfile")

	EmailServerAddr, _ = conf.String("email", "email_server_addr")
	EmailServerPort, _ = conf.String("email", "email_server_port")
	EmailAccount, _ = conf.String("email", "email_account")
	EmailPassword, _ = conf.String("email", "email_password")
	EmailToList, _ = conf.String("email", "email_tolist")
	EmailDuration, _ = conf.Int("email", "email_duration")

	return nil
}
Exemplo n.º 4
0
func init() {
	flagset := flag.NewFlagSet("config", flag.ContinueOnError)
	flagset.StringVar(&configFile, "config", "", "Config File")
	flagset.StringVar(&uuid, "uuid", "", "uuid")

	args, _ := SplitFlagsetFromArgs(flagset, os.Args[1:])
	flagset.Parse(args)

	// Ensure we have a UUID
	if uuid == "" {
		uuid = NewUUID()
	}

	if configFile == "" {
		for _, f := range defaultConfigFiles {
			if _, err := os.Stat(f); err == nil {
				configFile = f
				break
			}
		}
	}

	if configFile == "" {
		log.Println(log.ERROR, "Failed to find config file")
		conf = config.NewDefault()
		return
	}

	if _, err := os.Stat(configFile); os.IsNotExist(err) {
		log.Println(log.ERROR, "Config file does not exist", err)
		conf = config.NewDefault()
		return
	}

	var err error
	if conf, err = config.ReadDefault(configFile); err != nil {
		conf = config.NewDefault()
		log.Fatal(err)
	}

	// Set default log level from config, this can be overriden at the service level when the service is created
	if l, err := conf.RawStringDefault("log.level"); err == nil {
		log.SetLogLevel(log.LevelFromString(l))
	}

	// Set default log level from config, this can be overriden at the service level when the service is created
	if lh, err := conf.RawStringDefault("log.sysloghost"); err == nil {
		log.SetSyslogHost(lh)
	}

	// Set syslog port
	if i, err := conf.Int("DEFAULT", "log.syslogport"); err == nil {
		log.SetSyslogPort(i)
	}

	// Set GOMAXPROCS
	if i, err := conf.Int("DEFAULT", "runtime.gomaxprocs"); err == nil {
		runtime.GOMAXPROCS(i)
	}
}
Exemplo n.º 5
0
func LoginHandler(w http.ResponseWriter, r *http.Request, session sessions.Session, log *log.Logger) string {
	c, err := config.ReadDefault("users.cfg")

	if err != nil {
		return "Can't login. Problems reading user and password."
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	allowedUsername, _ := c.RawStringDefault("user")
	allowedPassword, _ := c.RawStringDefault("password")

	if username == allowedUsername && password == allowedPassword {

		log.Print("User WAS logged in.")

		session.Set("username", username)
		session.Set("password", password)
		http.Redirect(w, r, "/home", http.StatusFound)
		return "OK"
	}

	log.Print("User wasn't logged in. User " + username + " and password " + password)

	http.Redirect(w, r, "/login", http.StatusFound)
	return "Username or password incorrect"
}
Exemplo n.º 6
0
func loadConfig() {
	var err error
	Config, err = config.ReadDefault("app.conf")
	if err != nil {
		log.Fatalf("Error loading config. ERR: %+v", err)
	}
}
Exemplo n.º 7
0
//发送邮件
func sendMail(subject, content string, tos []string) {
	fmt.Println("发送邮件")
	mailer := &mail.Mailer{}
	from := ""
	if mailer.UserName == "" {
		//basePath := revel.BasePath
		//c, _ := config.ReadDefault(basePath + "/conf/qishare.conf")
		c, _ := config.ReadDefault(revel.BasePath + "/conf/qishare.conf")
		/*mailer.UserName, _ = c.String("smtp", "smtp.username")
		mailer.Password, _ = c.String("smtp", "smtp.password")
		from, _ = c.String("smtp", "smtp.from")
		mailer.Server, _ = c.String("smtp", "smtp.server")
		mailer.Port, _ = c.Int("smtp", "smtp.port")*/
		fmt.Println("BasePath" + revel.BasePath)
		fmt.Println(c)
		mailer.UserName = "******"
		mailer.Password = "******"
		from = "*****@*****.**"
		mailer.Server = "smtp.sina.com"
		mailer.Port = 25
	}
	//mailer := &mail.Mailer{Server: "smtp.sina.com", Port: 25, UserName: "******", Password: "******"}
	message := &mail.Message{From: from, To: tos, Subject: subject, PlainBody: bytes.NewBufferString(content)}

	err := mailer.SendMessage(message)
	if err != nil {
		fmt.Println(err)
	}
}
Exemplo n.º 8
0
func main() {

	//db access for releases
	db, err := sql.Open("sqlite3", "./release.db")
	if err != nil {
		panic(err.Error())
	}
	reldb := &gorp.DbMap{Db: db, Dialect: gorp.SqliteDialect{}}
	reldb.AddTableWithName(town.Release{}, "release").SetKeys(false, "Checksum").ColMap("Checksum").SetUnique(true).SetNotNull(true)
	reldb.CreateTablesIfNotExists()

	//db for logs
	//different database cause of locks with high log frequency
	dblog, err := sql.Open("sqlite3", "./logs.db")
	dbmap := &gorp.DbMap{Db: dblog, Dialect: gorp.SqliteDialect{}}
	dbmap.AddTableWithName(mydb.Log{}, "log").SetKeys(true, "Uid")
	dbmap.CreateTablesIfNotExists()
	logdb := mydb.DBLog{DB: dbmap}
	if err != nil {
		panic(err.Error())
	}

	logging.SetOutput(logdb)

	//read config file
	c, _ := config.ReadDefault("default.ini")

	//webserver
	serv := &webserv.Server{Config: c, RelDB: reldb, LogDB: dbmap}
	serv.Init()

}
Exemplo n.º 9
0
func register(ctx *cli.Context) {

	fn := path.Join(ctx.String("directory"), ".gomr")

	newTags := strings.Split(ctx.String("tag"), ",")

	if ctx.Bool("append") {
		if _, err := os.Stat(fn); err == nil {
			cfg, _ := config.ReadDefault(".gomr")
			curTags, _ := cfg.String("gomr", "tags")

			for _, tag := range strings.Split(curTags, ",") {
				newTags = AppendIfMissing(newTags, tag)
			}
		} else {
			err := "append used, existing file not found."
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
	}

	outTags := strings.Join(newTags, ",")

	outCfg := config.NewDefault()
	outCfg.AddSection("gomr")
	outCfg.AddOption("gomr", "tags", outTags)
	outCfg.WriteFile(fn, 0644, "gomr configuration file")

	return
}
Exemplo n.º 10
0
Arquivo: comm.go Projeto: jsli/gorevel
func sendMail(subject, content string, tos []string) error {
	message := `From: Revel社区
To: ` + strings.Join(tos, ",") + `
Subject: ` + subject + `
Content-Type: text/html;charset=UTF-8

` + content
	if Smtp.username == "" {
		path, _ := filepath.Abs("")
		c, _ := config.ReadDefault(fmt.Sprintf("%s/src/revelapp/conf/my.conf", path))

		Smtp.username, _ = c.String("smtp", "smtp.username")
		Smtp.password, _ = c.String("smtp", "smtp.password")
		Smtp.address, _ = c.String("smtp", "smtp.address")
		Smtp.from, _ = c.String("smtp", "smtp.from")
		Smtp.host, _ = c.String("smtp", "smtp.host")
	}

	auth := smtp.PlainAuth("", Smtp.username, Smtp.password, Smtp.host)
	err := smtp.SendMail(Smtp.address, auth, Smtp.from, tos, []byte(message))
	if err != nil {
		fmt.Println(err)
		return err
	}

	return nil
}
Exemplo n.º 11
0
func Init() {
	c, err := config.ReadDefault(revel.BasePath + "/conf/my.conf")
	driver, _ := c.String("database", "db.driver")
	dbname, _ := c.String("database", "db.dbname")
	user, _ := c.String("database", "db.user")
	password, _ := c.String("database", "db.password")
	host, _ := c.String("database", "db.host")

	params := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=true", user, password, host, dbname)
	Engine, err = xorm.NewEngine(driver, params)
	if err != nil {
		panic(err)
	}
	Engine.ShowSQL = revel.DevMode
	err = Engine.Sync(
		new(User),
		new(Category),
		new(Movie),
		// new(Reply),
		// new(Permissions),
	)

	if err != nil {
		panic(err)
	}
}
Exemplo n.º 12
0
func loadConfig() (err error) {
	Config, err = config.ReadDefault("../app.conf")
	if err != nil {
		log.Fatalf("Failed to read configs. ERR: %+v", err)
	}
	return err
}
Exemplo n.º 13
0
func ReadIniFile(inifile string) error {
	conf, err := config.ReadDefault(inifile)
	if err != nil {
		return fmt.Errorf("Read %v error. %v", inifile, err.Error())
	}

	Addr, _ = conf.String("service", "addr")
	NumCpu, _ = conf.Int("service", "num_cpu")
	AcceptTimeout, _ = conf.Int("service", "accept_timeout")
	ReadTimeout, _ = conf.Int("service", "read_timeout")
	WriteTimeout, _ = conf.Int("service", "write_timeout")

	C2COfflinemsgRedisAddr, _ = conf.String("redisdb", "c2c_offlinemsg_redisAddr")
	C2COfflinemsgRedisKeyExpireDay, _ = conf.String("redisdb", "c2c_offlinemsg_redisKeyExpireDay")

	LogFile, _ = conf.String("debug", "logfile")

	EmailServerAddr, _ = conf.String("email", "email_server_addr")
	EmailServerPort, _ = conf.String("email", "email_server_port")
	EmailAccount, _ = conf.String("email", "email_account")
	EmailPassword, _ = conf.String("email", "email_password")
	EmailToList, _ = conf.String("email", "email_tolist")
	EmailDuration, _ = conf.Int("email", "email_duration")

	return nil
}
Exemplo n.º 14
0
Arquivo: init.go Projeto: qmdx/GoCMS
//设置数据库
func SetDB() {
	path, _ := filepath.Abs("")
	c, _ := config.ReadDefault(fmt.Sprintf("%s/admin/conf/databases.conf", path))

	driver, _ := c.String("database", "db.driver")
	dbname, _ := c.String("database", "db.dbname")
	user, _ := c.String("database", "db.user")
	password, _ := c.String("database", "db.password")
	host, _ := c.String("database", "db.host")
	//prefix, _ := c.String("database", "db.prefix")

	//数据库链接
	var err error
	Engine, err = xorm.NewEngine(driver, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", user, password, host, dbname))
	if err != nil {
		revel.WARN.Printf("错误: %v", err)
	}

	//缓存方式是存放到内存中,缓存struct的记录数为1000条
	//cacher := xorm.NewLRUCacher(xorm.NewMemoryStore(), 1000)
	//Engine.SetDefaultCacher(cacher)

	//控制台打印SQL语句
	//Engine.ShowSQL = true

	//控制台打印调试信息
	//Engine.ShowDebug = true

	//控制台打印错误信息
	//Engine.ShowErr = true

	//控制台打印警告信息
	//Engine.ShowWarn = true
}
Exemplo n.º 15
0
func ParseConfig(configPath string) (ci ConfigInfo, err error) {
	conf, err := config.ReadDefault(configPath)
	if err != nil {
		return
	}
	businessList, _ := conf.String("mode", "BusinessList")
	masterConf, _ := conf.String("master", "MasterConf")
	masterRestartScript, _ := conf.String("master", "MasterRestartScript")

	copyMethod, _ := conf.Int("slave", "CopyMethod")
	slaveServerIp, _ := conf.String("slave", "SlaveServerIp")
	slaveServerSSHPort, _ := conf.Int("slave", "SlaveServerSSHPort")
	slaveRemoteUser, _ := conf.String("slave", "SlaveRemoteUser")
	slaveRemotePasswd, _ := conf.String("slave", "SlaveRemotePasswd")
	sshCommandPath, _ := conf.String("slave", "SSHCommandPath")
	scpCommandPath, _ := conf.String("slave", "ScpCommandPath")

	slaveConf, _ := conf.String("slave", "SlaveConf")
	slaveRestartScript, _ := conf.String("slave", "SlaveRestartScript")

	storeScheme, _ := conf.Int("store", "StoreScheme")

	dbDriverName, _ := conf.String("store", "DBDriverName")
	dbDataSourceName, _ := conf.String("store", "DBDataSourceName")

	fileToReplaceDB, _ := conf.String("store", "FileToReplaceDB")

	masterStatsPage, _ := conf.String("stats", "MasterStatsPage")
	slaveStatsPage, _ := conf.String("stats", "SlaveStatsPage")

	vip, _ := conf.String("others", "Vip")

	newHAProxyConfPath, _ := conf.String("others", "NewHAProxyConfPath")

	ci = ConfigInfo{
		BusinessList:        businessList,
		MasterConf:          masterConf,
		MasterRestartScript: masterRestartScript,
		CopyMethod:          copyMethod,
		SlaveServerIp:       slaveServerIp,
		SlaveServerSSHPort:  slaveServerSSHPort,
		SlaveRemoteUser:     slaveRemoteUser,
		SlaveRemotePasswd:   slaveRemotePasswd,
		SSHCommandPath:      sshCommandPath,
		ScpCommandPath:      scpCommandPath,
		SlaveConf:           slaveConf,
		SlaveRestartScript:  slaveRestartScript,
		StoreScheme:         storeScheme,
		DBDriverName:        dbDriverName,
		DBDataSourceName:    dbDataSourceName,
		FileToReplaceDB:     fileToReplaceDB,
		MasterStatsPage:     masterStatsPage,
		SlaveStatsPage:      slaveStatsPage,
		Vip:                 vip,
		NewHAProxyConfPath:  newHAProxyConfPath,
	}
	err = CheckConfig(ci)
	return
}
Exemplo n.º 16
0
// filepath E.g. ""/etc/someconfig.cfg"
func NewReader(filepath string) (reader *Reader, err error) {
	config, err := config.ReadDefault(filepath)
	if err != nil {
		return nil, err
	}

	return &Reader{config: config}, nil
}
Exemplo n.º 17
0
func LoadConfig(confName string) (*MergedConfig, error) {
	conf, err := config.ReadDefault(confName)
	if err == nil {
		return &MergedConfig{conf, ""}, nil
	}

	return nil, err
}
Exemplo n.º 18
0
func (ct *ConfigTools) InitSelf(configpath string) {
	fmt.Println("ConfigTools initself")
	// cfg, err := config.ReadDefault("./config.conf")
	cfg, err := config.ReadDefault(configpath)
	if err != nil {
		fmt.Printf("config.ReadDefault error:%v\n", err)
		panic(fmt.Sprintf("config.ReadDefault error:%v", err))
		return
	}
	driver, _ := cfg.String("database", "db.driver")
	dbname, _ := cfg.String("database", "db.dbname")
	user, _ := cfg.String("database", "db.user")
	password, _ := cfg.String("database", "db.password")
	host, _ := cfg.String("database", "db.host")
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true", user, password, host, dbname)

	ct.OrmEngine, err = xorm.NewEngine(driver, dataSourceName)
	if err != nil {
		fmt.Printf("xorm.NewEngine error:%v\n", err)
		panic(fmt.Sprintf("xorm.NewEngine error:%v", err))
	}
	ct.OrmEngine.Charset("utf8mb4")

	rdhost, _ := cfg.String("redis", "rd.host-master")
	rdpwd, _ := cfg.String("redis", "rd.pwd")
	ct.Redisclient = qqredis.NewRedisCache(rdhost, rdpwd, 2000)
	//------log
	logpath, _ := cfg.String("log", "log.path")
	common.SetConsole(true)
	// common.SetLevel(common.INFO)
	common.SetLevel(common.WARN)
	common.SetRollingDaily(logpath)

	rule, cfgerr := cfg.String("maunal", "runrule")
	if cfgerr == nil {
		ct.Runrule, _ = strconv.Atoi(rule)
	} else {
		ct.Runrule = 0
	}
	isproc, cfgerr := cfg.String("maunal", "isproc")
	if cfgerr == nil {
		ct.IsProc, _ = strconv.Atoi(isproc)
	} else {
		ct.IsProc = 0
	}

	portstr, cfgerr := cfg.String("web", "port")
	if cfgerr == nil {
		ct.HttpPort, _ = strconv.Atoi(portstr)
	}
	if ct.HttpPort == 0 {
		ct.HttpPort = 8999
	}

	ct.IpPath, _ = cfg.String("web", "ippath")
	ct.UserAgentPath, _ = cfg.String("web", "useragentpath")
}
Exemplo n.º 19
0
//获取配置文件信息
func GetConfig(section string, option string) string {
	c, _ := config.ReadDefault("conf/config.cfg")
	value, err := c.String(section, option)
	if err != nil {
		fmt.Println("读取配置文件出错", err)
		return ""
	}
	return value
}
Exemplo n.º 20
0
// Create a new config by reading from a config file, for a given environment.
func ReadConfig(file, env string) (*Config, error) {
	cfg, err := config.ReadDefault(file)
	if err != nil {
		return nil, err
	}

	c := &Config{cfg, env}
	return c, nil
}
Exemplo n.º 21
0
func ReadConfig() (*Config, error) {
	ini, err := config.ReadDefault(path.Join(configDir(), hiddenPrefix+"oysterconfig"))
	if err != nil {
		if os.IsNotExist(err) {
			return NewConfig(), nil
		}
		return nil, err
	}
	return &Config{ini: ini}, nil
}
Exemplo n.º 22
0
func initConfig(paths []string) {
	if len(paths) == 1 {
		once.Do(func() {
			var err error

			conf, err = c.ReadDefault(paths[0])
			hc.CheckError(err)
		})
	}
}
Exemplo n.º 23
0
func Init() {
	//uploadPath := basePath + "/public/upload/"
	c, _ := config.ReadDefault(revel.BasePath + "/conf/qishare.conf")
	driver, _ := c.String("database", "db.driver")
	dbname, _ := c.String("database", "db.dbname")
	user, _ := c.String("database", "db.user")
	password, _ := c.String("database", "db.password")
	host, _ := c.String("database", "db.host")
	connectDb(driver, dbname, user, password, host)
}
Exemplo n.º 24
0
func Set(key string, value string) string {
	ItExists()

	conf.AddOption("default", key, value)
	conf.WriteFile(hubrc, 0600, "Config for http://github.com/pksunkara/hub")

	conf, _ = config.ReadDefault(hubrc)

	return value
}
Exemplo n.º 25
0
func New() Harvest {
	c, err := config.ReadDefault(getHome() + "/.garvest.cfg")
	if err != nil {
		log.Fatal(err)
	}
	domain, _ := c.String("api", "domain")
	username, _ := c.String("auth", "username")
	password, _ := c.String("auth", "password")
	return Harvest{domain: domain, username: username, password: password}
}
Exemplo n.º 26
0
func main() {

	flag.BoolVar(&verbose, "verbose", false, "See lots of stuff")
	confFile := flag.String("config", "", "Config file location")
	flag.Parse()

	var (
		protocol string
		host     string
		port     string
		db       string
		user     string
		password string
		err      error
		c        *config.Config
	)

	c, err = config.ReadDefault(*confFile)
	if err != nil {
		log.Print("No config file found, using defaults")
		protocol = "http://"
		host = "localhost"
		port = "8086"
		db = "events"
		user = "******"
		password = "******"
	} else {

		if protocol, err = c.RawStringDefault("protocol"); err != nil {
			protocol = "http://"
		}
		if host, err = c.RawStringDefault("host"); err != nil {
			host = "localhost"
		}
		if db, err = c.RawStringDefault("db"); err != nil {
			db = "events"
		}
		if user, err = c.RawStringDefault("user"); err != nil {
			user = "******"
		}
		if user, err = c.RawStringDefault("password"); err != nil {
			user = "******"
		}
	}

	influxUrl = protocol + host + ":" + port + "/db/" + db + "/series?u=" + user + "&p=" + password

	if verbose {
		log.Print("Starting proxy")
		log.Print("InfluxDB URL : " + influxUrl)
	}

	http.HandleFunc("/", handler)
	http.ListenAndServe(":8079", nil)
}
Exemplo n.º 27
0
func LoadContext(confName string, confPaths []string) (*Context, error) {
	var err error
	var conf *config.Config
	for _, confPath := range confPaths {
		conf, err = config.ReadDefault(path.Join(confPath, confName))
		if err == nil {
			return &Context{config: conf}, nil
		}
	}
	return nil, err
}
Exemplo n.º 28
0
func ItExists() {
	usr, _ := user.Current()
	hubrc = filepath.Join(usr.HomeDir, ".hubrc")

	var err error

	// Load config for application
	conf, err = config.ReadDefault(hubrc)

	if err != nil {
		conf = config.NewDefault()

		conf.AddSection("default")
		conf.AddOption("default", "site", "github.com")
		conf.AddOption("default", "combine", "0")

		conf.WriteFile(hubrc, 0600, "Config for http://github.com/pksunkara/hub")
		conf, _ = config.ReadDefault(hubrc)
	}
}
Exemplo n.º 29
0
Arquivo: init.go Projeto: jsli/gorevel
func init() {
	path, _ := filepath.Abs("")
	c, _ := config.ReadDefault(fmt.Sprintf("%s/src/revelapp/conf/my.conf", path))

	driver, _ := c.String("database", "db.driver")
	dbname, _ := c.String("database", "db.dbname")
	user, _ := c.String("database", "db.user")
	password, _ := c.String("database", "db.password")
	host, _ := c.String("database", "db.host")

	RegisterDb(driver, dbname, user, password, host)
}
Exemplo n.º 30
0
func main() {
	flag.Parse()

	conf, err := config.ReadDefault(*configFile)
	if err != nil {
		conf = config.NewDefault()
		fmt.Printf("Error loading config file")
	}

	log.SetFlags(log.Ldate | log.Ltime)
	logDir, _ := conf.String("DEFAULT", "log_dir")
	if logDir == "" {
		logDir = "."
	}

	filePrefix := "twitch_stats-"
	fnTime := time.Now().UTC().Format("200601")

	logFile := fmt.Sprintf("%s/%s%s.log", logDir, filePrefix, fnTime)
	fp, err := os.OpenFile(logFile, os.O_CREATE|os.O_APPEND|os.O_SYNC|os.O_WRONLY, 0644)
	if err != nil {
		fmt.Printf("Failed to open log file '%s': %s", logFile, err)
	}

	log.SetOutput(fp)

	keyid, _ := conf.Int("DEFAULT", "KeyID")
	vcode, _ := conf.String("DEFAULT", "vCode")
	listenOn, _ := conf.String("DEFAULT", "listen")

	initDB()

	//Setup the timer. This pulls notifications from the API every 21 minutes. The cache timer is 20 minutes, so it should be ok.
	//Some endeavouring dev could probably modify this so that it gets the cache timer from the API and checks at that time, but :effort:
	t := time.NewTicker(time.Minute * 21).C
	go func() {
		for {
			select {
			case <-t:
				getNotifications(keyid, vcode)
			}
		}
	}()

	//This is the part that listens and handles the incoming http connections.
	http.HandleFunc("/", getStats)

	//This part is so that the static files actually load, mainly the css and js shit.
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	http.ListenAndServe(listenOn, nil)

}