func main() { if !*logOnStdout { logFile, _ := os.OpenFile(*logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) log.SetOutput(logFile) } log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) cnfg, err := config.ReadDefault(*configFileName) if err != nil { log.Println("Fail to find", *configFileName, err) return } configSection := "db" if cnfg.HasSection(configSection) { f := func(key string) string { value, err := cnfg.String(configSection, key) if err != nil { log.Println("Config file", *configFileName, "Failt to find key", key, err) return "" } return value } err = ephenationdb.SetConnection(f) if err != nil { log.Println("main: open DB:", err) return } } else { log.Println("Config file", configFileName, "missing, or no section 'db'") } db := ephenationdb.New() chunkdata(db.C("chunkdata")) }
func Set(section, key, value string) { flag.Parse() cfg, _ := config.ReadDefault(*configFile) if cfg.AddOption(section, key, value) { cfg.WriteFile(con, 0644, "General configuration file") } }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.Parse() //set config file std cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile, err) } //set config file std End //Initialized topic from the configuration if cfg.HasSection("topicArr") { section, err := cfg.SectionOptions("topicArr") if err == nil { for _, v := range section { options, err := cfg.String("topicArr", v) if err == nil { TOPIC[v] = options } } } } //Initialized topic from the configuration END fmt.Println(TOPIC) fmt.Println(TOPIC["debug"]) }
func main() { flag.Parse() cfgFile := flag.String("conf", "redis_ha.conf", "General configuration file") var cfg *config.Config cfg, err := config.ReadDefault(*cfgFile) if err != nil { log.Criticalf("Fail to find", *cfgFile, err) } // Get the logfile config logCfgFile, _ := cfg.String(S_SEC_PUBCONF, SC_SEELOG_CFG_FILE) InitSeeLog(logCfgFile) log.Info("REDIS HIGH AVAILABITY START") // Parse the config ParseConfig(cfg) log.Infof("Sentinel host: %s", gSentinelHost) // Get the master, and slave gRedisPool = RedisPoolConn() // create zknodes gZKConn = ZKConnect() for item := range gHANodeMap { haNode := gHANodeMap[item] GetRedisMaster(haNode) GetRedisSlaves(haNode) fmt.Printf("%s Master=%s\n", item, haNode.Master) for e := haNode.Slaves.Front(); e != nil; e = e.Next() { fmt.Printf("Slave=%s\n", e.Value.(string)) } CreateRecursivePath(haNode.ZooMaster) CreateRecursivePath(haNode.ZooSlave) CreateAllNodes(haNode) } go RecoveryMain() MonitorSentinel() for { /* gConn, err = redis.Dial("tcp", gSentinelHost) if err != nil { log.Criticalf("Connect to sentinel error:%s", err.Error()) continue } */ MonitorSentinel() time.Sleep(1e9) } defer gZKConn.Close() }
func Get(section string, key string) string { flag.Parse() cfg, err := config.ReadDefault(*configFile) if err != nil { return "" } v, err := cfg.String(section, key) if err != nil { return "" } return v }
func LoadConfig(configFilePath string) (*Config, error) { apiConfig := new(Config) cfg, err := config.ReadDefault(configFilePath) if err != nil { return nil, fmt.Errorf("Fail to find config, path: %s err: %s", configFilePath, err) } if cfg.HasSection("default") { apiConfig.DBHost, _ = cfg.String("default", "DBHost") apiConfig.DBPort, _ = cfg.Int("default", "DBPort") apiConfig.DBUser, _ = cfg.String("default", "DBUser") apiConfig.DBPasswd, _ = cfg.String("default", "DBPasswd") apiConfig.DB, _ = cfg.String("default", "DBName") apiConfig.HTTPHost, _ = cfg.String("default", "HTTPHost") apiConfig.HTTPPort, _ = cfg.Int("default", "HTTPPort") apiConfig.AgentPort, _ = cfg.Int("default", "AgentPort") apiConfig.InnodbWeight, _ = cfg.Float("default", "InnodbSizeWeight") apiConfig.AESSalt, _ = cfg.String("default", "AesSalt") apiConfig.Img_Ref, _ = cfg.String("default", "Img_Ref") apiConfig.Network_uuid, _ = cfg.String("default", "Network_uuid") apiConfig.Network_Name, _ = cfg.String("default", "Network_Name") apiConfig.Default_Root_Pwd, _ = cfg.String("default", "Default_Root_Pwd") apiConfig.Host_Keystone, _ = cfg.String("default", "Host_Keystone") apiConfig.Host_Nova, _ = cfg.String("default", "Host_Nova") apiConfig.Host_Neutron, _ = cfg.String("default", "Host_Neutron") apiConfig.Jdos_User, _ = cfg.String("default", "Jdos_User") apiConfig.Jdos_Pwd, _ = cfg.String("default", "Jdos_Pwd") apiConfig.SlaveIoRunning, _ = cfg.String("default", "SlaveIoRunning") apiConfig.SlaveSqlRunning, _ = cfg.String("default", "SlaveSqlRunning") apiConfig.SecondsBehindMaster, _ = cfg.Int("default", "SecondsBehindMaster") apiConfig.TimeoutUpdate, _ = cfg.Int("default", "TimeoutUpdate") apiConfig.ChargeUrl, _ = cfg.String("default", "ChargeUrl") apiConfig.ChargeIdentity, _ = cfg.String("default", "ChargeIdentity") apiConfig.ChargeAccesskey, _ = cfg.String("default", "ChargeAccesskey") apiConfig.LocationService, _ = cfg.String("default", "LocationService") apiConfig.HagroupDBPort, _ = cfg.Int("default", "HagroupDBPort") apiConfig.ProcessStatus, _ = cfg.Int("default", "ProcessStatus") } fmt.Println(apiConfig) return apiConfig, nil }
// The 'name' argument is not the nick name shown, it is the login name used to // authenticate the player. func (up *user) CmdLogin_WLwWLuWLqBlWLc(email string) { // fmt.Printf("CmdLogin: New player %v\n", email) // It may be that there is no license for this player. But we can only give one type of error // message, which means wrong email or password. validTestUser := false remote := up.conn.RemoteAddr().String() addr := strings.Split(remote, ":") // The format is expected to be NNN.NNN.NNN.NNN:NNNN. if *allowTestUser && strings.HasPrefix(email, CnfgTestPlayerNamePrefix) { if len(addr) == 2 { ip := addr[0] cnfg, err := config.ReadDefault(*configFileName) if err == nil && cnfg.HasSection("login") { testplayersallowed, _ := cnfg.Bool("login", "testplayer") testiplist, err := cnfg.String("login", "testip") if testplayersallowed && err == nil && strings.Contains(testiplist, ip) { validTestUser = true } else if err != nil { validTestUser = true // Allow testuser if no "testip" key. } } else { validTestUser = true // Allow testuser if no config file or no "Login" section } } } else if strings.HasPrefix(email, CnfgTestPlayerNamePrefix) { log.Println("Denied testuser from", remote) } if validTestUser { // This test player is allowed login without password, but it is never saved up.New_WLwWLc(email) up.loginAck_WLuWLqBlWLa() up.AdminLevel = 9 } else { ok := up.Load_WLwBlWLc(email) up.challenge = make([]byte, LoginChallengeLength) cryptrand.Read(up.challenge) if !ok && *verboseFlag > 0 { log.Printf("Login failed or no license for '%v'\n", email) // We know login failed already, but don't termibate here. Wait // until player has given the password. The reason is that there // shall be the error if the email is wrong or the password is wrong. } up.connState = PlayerConnStatePass // Request a password, even though the license may be incorrect. up.writeBlocking_Bl([]byte{3 + LoginChallengeLength, 0, client_prot.CMD_REQ_PASSWORD}) up.writeBlocking_Bl(up.challenge) } }
// Extract the version of the current client from the config file. This is done // repeatedly, which means the definition can be changed "live", while the server is running. func LoadClientVersionInformation() (int, int) { cnfg, err := config.ReadDefault(*configFileName) if err == nil && cnfg.HasSection("client") { major, err := cnfg.Int("client", "major") if err != nil { log.Println(*configFileName, "major:", err) return 0, 0 } minor, err := cnfg.Int("client", "minor") if err != nil { log.Println(*configFileName, "minor:", err) return 0, 0 } return major, minor } return 0, 0 }
func initServer() error { configMap := make(map[string]ApplicationConfig) cfg, err := config.ReadDefault("config.ini") if err != nil { return Error("unable to open config file or wrong fomart") } sections := cfg.Sections() if len(sections) == 0 { return Error("no app config") } for _, section := range sections { if section != "DEFAULT" { sectionData, _ := cfg.SectionOptions(section) tmp := make(map[string]string) for _, key := range sectionData { value, err := cfg.String(section, key) if err == nil { tmp[key] = value } } maxClientConn, _ := strconv.Atoi(tmp["MaxClientConn"]) configMap[section] = ApplicationConfig{tmp["AppId"], tmp["AppSecret"], maxClientConn, tmp["GetConnectApi"], tmp["LoseConnectApi"], tmp["MessageTransferApi"]} } } fmt.Println(configMap) valid_config := make(map[string]ApplicationConfig) for appid, appconfig := range configMap { // if appconfig.TokenMethod != TOKEN_METHOD_GET && appconfig.TokenMethod != TOKEN_METHOD_COOKIE{ // return Error("invalid TokenMethod appid: " + appid ) // } if appconfig.MaxClientConn < 1 || appconfig.MaxClientConn > MAX_CLIENT_CONN { return Error("invalid MaxClientConn appid: " + appid) } channelGroup := make(map[string]ChannelService) app := Application{channelGroup, appconfig} applications[appid] = app valid_config[appid] = appconfig } applications_config = valid_config return nil }
func (this *ConfigHelper) LoadConfig(configFile *string) { cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find config file", *configFile) } //Initialized topic from the configuration if cfg.HasSection(TOPICSECTION) { section, err := cfg.SectionOptions(TOPICSECTION) if err == nil { for _, v := range section { options, err := cfg.String(TOPICSECTION, v) if err == nil { TOPIC[v] = options } } } } fmt.Println(TOPIC) }
func main() { log.SetFlags(log.LstdFlags | log.Llongfile) m := getMartini() store := sessions.NewCookieStore([]byte("secret123")) m.Use(sessions.Sessions("goodshare_session", store)) m.Use(martini.Static("static")) m.Use(render.Renderer()) //配置文件 configFile := flag.String("configfile", "config.ini", "配置文件") inicfg, err := config.ReadDefault(*configFile) if err != nil { panic(err) } m.Map(inicfg) //数据库 db := util.GetDB(inicfg) m.Map(db) //缓存 cache := make(map[string]interface{}) m.Map(cache) m.Any("/login", auth.Login) m.Any("/refresh", auth.Refresh) m.Any("/register", auth.Register) m.Get("/logout", auth.Logout) m.Any("/share", auth.Share, auth.Auth) m.Get("/init", getinit) m.Get("/items", items) m.Any("/img/upload", imgupload) m.Group("/video", video.Router) m.Post("/img/delete", imgdelete) m.Get("/", index) //静态内容 // m.Use(martini.Static("static")) //需要权限的内容 // m.Group("/admin", admin.Router, auth.Auth) m.Run() //m.RunOnAddr(":3333") }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) flag.Parse() cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile, err) } if cfg.HasSection("topicArr") { section, err := cfg.SectionOptions("topicArr") if err == nil { for _, v := range section { options, err := cfg.String("topicArr", v) if err == nil { TOPIC[v] = options } } } } fmt.Println(TOPIC) fmt.Println(TOPIC["addr"]) fmt.Println(TOPIC["debug"]) }
/*读取ini配置文件*/ func GetConfig(configFile *string, sectionFlag string) map[string]string { var DIRS = make(map[string]string) //set config file std cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile, err) } //Initialized from the configuration if cfg.HasSection(sectionFlag) { section, err := cfg.SectionOptions(sectionFlag) if err == nil { for _, v := range section { options, err := cfg.String(sectionFlag, v) if err == nil { DIRS[v] = options } } } } //Initialized dirs from the configuration END return DIRS }
/** * 读取配置文件的内容,返回数组 */ func ReadIni(cpath string, sec string) map[string]string { runtime.GOMAXPROCS(runtime.NumCPU()) flag.Parse() var rs = make(map[string]string) configFile := flag.String("configfile", cpath, "General configuration file") cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile, err) } if cfg.HasSection(sec) { section, err := cfg.SectionOptions(sec) if err == nil { for _, v := range section { options, err := cfg.String(sec, v) if err == nil { rs[v] = options } } } } return rs }
func dbconfParse(key string) (conf map[string]string) { conf = make(map[string]string) flag.Parse() //set config file std cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile) } if cfg.HasSection(key) { section, err := cfg.SectionOptions(key) if err == nil { for _, v := range section { options, err := cfg.String(key, v) if err == nil { conf[v] = options } } } } return }
func loadConf() map[string]interface{} { flag.Parse() //set config file std cfg, err := config.ReadDefault(*configFile) if err != nil { log.Fatalf("Fail to find", *configFile, err) } if cfg.HasSection("topic") { section, err := cfg.SectionOptions("topic") if err == nil { for _, v := range section { options, err := cfg.String("topic", v) if err == nil { settings[v] = options } else { log.Fatal(err) } } } else { log.Fatal(err) } } return settings }
func read_config_file(config_file string, zone string) bool { cfg, err := config.ReadDefault(config_file) if err != nil { return false } config_params := make(map[string]string) if cfg.HasSection(zone) { section, err := cfg.SectionOptions(zone) if err == nil { for _, v := range section { options, err := cfg.String(zone, v) if err == nil { config_params[v] = options } } } else { return false } } else { return false } if len(config_params["record_path"]) > 0 { record_path := config_params["record_path"] if record_path[len(record_path)-1] != '/' { record_path = record_path + "/" } g_gout_config.record_path = record_path } else { return false } if len(config_params["timeout"]) > 0 { str_timeout := config_params["timeout"] timeout_len := len(str_timeout) unit := 1 if str_timeout[timeout_len-1] == 's' { timeout_len-- } else if str_timeout[timeout_len-1] == 'm' { timeout_len-- unit = 60 } timeout, _ := strconv.ParseInt(str_timeout[:timeout_len], 10, 64) g_gout_config.timeout = timeout * int64(unit) } else { return false } if len(config_params["check_time"]) > 0 { str_check_time := config_params["check_time"] check_time_len := len(str_check_time) unit := 1 if str_check_time[check_time_len-1] == 's' { check_time_len-- } else if str_check_time[check_time_len-1] == 'm' { check_time_len-- unit = 60 } check_time, _ := strconv.ParseInt(str_check_time[:check_time_len], 10, 64) g_gout_config.check_time = check_time * int64(unit) } else { return false } if len(config_params["log_file"]) > 0 { g_gout_config.log_file = fmt.Sprintf("%s%s", g_default_path, config_params["log_file"]) } else { return false } g_gout_config.log_level = config_params["log_level"] return true }
func main() { flag.Parse() if !*logOnStdout { logFile, _ := os.OpenFile(*logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) log.SetOutput(logFile) } log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) cnfg, err := config.ReadDefault(*configFileName) if err != nil { log.Println("Fail to find", *configFileName, err) return } configSection := "db" if cnfg.HasSection(configSection) { f := func(key string) string { value, err := cnfg.String(configSection, key) if err != nil { log.Println("Config file", *configFileName, "Failt to find key", key, err) return "" } return value } err = ephenationdb.SetConnection(f) if err != nil { log.Println("main: open DB:", err) // Continue without DB. Only test users can connect. } } else { log.Println("Config file", *configFileName, "missing section", configSection) } if encryptionSalt, err = cnfg.String("login", "salt"); err != nil { encryptionSalt = "" // Effectively no salt } if *createuser != "" { CreateUser(*createuser) return } if *convertChunkFiles { ConvertFiles() return } if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() // Also done from special command /shutdown } if *tflag { DoTest() return } log.Printf("Pheenadv world server\n") if *verboseFlag > 0 { log.Printf("Verbose flag set to %d\n", *verboseFlag) } if *inhibitCreateChunks { log.Println("No chunks will be created or saved") } runtime.GOMAXPROCS(*procFlag) rand.Seed(time.Now().UnixNano()) host, err := os.Hostname() if err != nil { panic(err) } log.Printf("Start world server on %s\n", host) if *allowTestUser { log.Printf("Testusers without password allowed\n") } err = SetupListenForClients_WLuBlWLqWLa(*ipPort) if err != nil { log.Printf("%v, server abort\n", err) os.Exit(1) } go ProcAutosave_RLu() go ProcPurgeOldChunks_WLw() go CatchSig() ManageMonsters_WLwWLuWLqWLmBlWLc() // Will not return }
// 解析配置文件 func ParseConfile(key string) { conf := make(map[string]string) cfg, err := config.ReadDefault(confile) if err != nil { fmt.Errorf("Failed Read cfile") } if cfg.HasSection(key) { section, err := cfg.SectionOptions(key) if err == nil { for _, v := range section { options, err := cfg.String(key, v) if err == nil { conf[v] = options } } } if v, ok := conf["host"]; ok { dsn.hostname = v } else { fmt.Errorf("Key:host Not Found In The Config file.") } if v, ok := conf["username"]; ok { dsn.username = v } else { fmt.Errorf("Key:username Not Found In The Config file.") } if v, ok := conf["password"]; ok { dsn.password = v } else { fmt.Errorf("Key:password Not Found In The Config file.") } if v, ok := conf["port"]; ok { dsn.port = v } else { fmt.Errorf("Key:port Not Found In The Config file.") } if v, ok := conf["timeout"]; ok { dsn.timeout = v } else { fmt.Errorf("Key:timeout Not Found In The Config file.") } if v, ok := conf["charset"]; ok { dsn.charset = v } else { fmt.Errorf("Key:charset Not Found In The Config file.") } if v, ok := conf["currentnums"]; ok { currentnums, _ = strconv.Atoi(v) } else { currentnums = CURRENTNUMS } if v, ok := conf["keepalived"]; ok { keepalived, _ = strconv.Atoi(v) } else { currentnums = KEEPALIVED } if v, ok := conf["logfile"]; ok { logfile = v } else { logfile = LOGFILE } if v, ok := conf["presstime"]; ok { presstime, _ = strconv.ParseInt(v, 10, 64) } else { presstime = PRESSTIME } if v, ok := conf["sqljson"]; ok { sqlfile = v } else { fmt.Errorf("Key:sqljson Not Found In The Config file.") } } else { fmt.Errorf("The conf file have no section %s", key) } }