func setEngine() { dbName := utils.Cfg.MustValue("db", "name") dbPwd := utils.Cfg.MustValue("db", "pwd_"+runtime.GOOS) if runtime.GOOS == "darwin" { u, err := user.Current() if err != nil { beego.Critical("models.init -> fail to get user:"******"db", "pwd_"+runtime.GOOS+"_"+u.Username) } var err error x, err = xorm.NewEngine("mysql", fmt.Sprintf("%v:%v@%v/%v?charset=utf8", utils.Cfg.MustValue("db", "user"), dbPwd, utils.Cfg.MustValue("db", "host"), dbName)) if err != nil { beego.Critical("models.init -> fail to conntect database:", err.Error()) os.Exit(2) } if beego.RunMode != "pro" { x.ShowDebug = true x.ShowErr = true //x.ShowSQL = true } beego.Trace("Initialized database ->", dbName) }
func dbInit() { orm.RegisterModel(new(UserInfo), new(UserStatus), new(UserRecord)) //register mysql driver err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } //register default database if !localSwitch { orm.RegisterDataBase("default", "mysql", "autelan:Autelan1202@tcp(rdsrenv7vrenv7v.mysql.rds.aliyuncs.com:3306)/umsdb?charset=utf8&&loc=Asia%2FShanghai") } else { dbIp := beego.AppConfig.String("DbIp") dbPort := beego.AppConfig.String("DbPort") dbName := beego.AppConfig.String("DbName") dbUser := beego.AppConfig.String("DbUser") dbPassword := beego.AppConfig.String("DbPassword") dbUrl := dbUser + ":" + dbPassword + "@tcp(" + dbIp + ":" + dbPort + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai" beego.Debug("dbUrl=", dbUrl) err = orm.RegisterDataBase("default", "mysql", dbUrl) if err != nil { beego.Critical(err) } } orm.SetMaxIdleConns("default", 30) orm.SetMaxOpenConns("default", 30) ormer = orm.NewOrm() }
func (n *NoteEntry) save() bool { appDataDb, err := leveldb.OpenFile(Configs["conf/db.conf"].String("app::path"), nil) if err != nil { beego.Error(err) beego.Critical("unable to open " + Configs["conf/db.conf"].String("app::path")) return false } defer appDataDb.Close() tmp := int64(1014) if urlCountStr, err := appDataDb.Get([]byte("urlCount"), nil); err == nil { tmp, _ = strconv.ParseInt(string(urlCountStr), 10, 64) } if tmp < urlCount && appDataDb.Put([]byte("urlCount"), []byte(strconv.FormatInt(urlCount, 10)), nil) != nil { beego.Critical("unable to save to db") return false } urlDb, err := leveldb.OpenFile(Configs["conf/db.conf"].String("url::path"), nil) if err != nil { beego.Critical("unable to open " + Configs["conf/db.conf"].String("url::path")) return false } defer urlDb.Close() if buf, err := json.Marshal(n.toPublic()); err != nil { beego.Error("unable to Marshal object", n) return false } else { urlDb.Put([]byte(n.url), buf, nil) } return true }
func init() { //register all tables orm.RegisterModel(new(Userinfo), new(Admininfo), new(Deviceinfo), new(Historyinfo), new(Command), new(OperationRecord), new(Alarm), new(Script)) //register mysql driver err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } //register default database dbIp := beego.AppConfig.String("DbIp") dbPort := beego.AppConfig.String("DbPort") dbName := beego.AppConfig.String("DbName") dbUser := beego.AppConfig.String("DbUser") dbPassword := beego.AppConfig.String("DbPassword") dbUrl := dbUser + ":" + dbPassword + "@tcp(" + dbIp + ":" + dbPort + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai" beego.Debug("dbUrl=", dbUrl) err = orm.RegisterDataBase("default", "mysql", dbUrl) if err != nil { beego.Critical(err) } //orm.RegisterDataBase("default", "mysql", "root:autelan@/lte_test?charset=utf8&&loc=Asia%2FShanghai") orm.SetMaxIdleConns("default", 30) orm.SetMaxOpenConns("default", 30) }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) beego.SetLogFuncCall(true) beego.SessionOn = true goth.UseProviders( gplus.New( beego.AppConfig.String("CLIENT_ID"), beego.AppConfig.String("CLIENT_SECRET"), beego.AppConfig.String("CLIENT_CALLBACK"), ), ) SessionTimeout, err := beego.AppConfig.Int("SESSION_TIMEOUT") if err != nil { beego.Critical(err) } SessionRefreshInterval, err := beego.AppConfig.Int("SESSION_REFRESH_INTERVAL") if err != nil { beego.Critical(err) } goJwt.Conf = goJwt.JwtConf{ PrivateKeyFile: beego.AppConfig.String("PrivateKeyFile"), PublicKeyFile: beego.AppConfig.String("PublicKeyFile"), Algorithm: beego.AppConfig.String("Algorithm"), SessionSecret: beego.AppConfig.String("SESSION_SECRET"), SessionName: beego.AppConfig.String("SESSION_NAME"), SessionTimeout: SessionTimeout, SessionRefreshInterval: SessionRefreshInterval, } goJwt.Configure() goJwt.Store = sessions.NewCookieStore([]byte(beego.AppConfig.String("SESSION_SECRET"))) ldapPort, err := beego.AppConfig.Int("Ldap_port") if err != nil { beego.Critical(err) } tim.Conf = tim.LdapConf{ Ldap_server: beego.AppConfig.String("Ldap_server"), Ldap_port: uint16(ldapPort), Base_dn: beego.AppConfig.String("Base_dn"), Ldap_user: beego.AppConfig.String("Ldap_user"), Ldap_pass: beego.AppConfig.String("Ldap_pass"), } beego.SetStaticPath("/public", "static") if err != nil { beego.Critical("Cannot connect to Redis: ", err) return } beego.Run() }
func RegisterDB() { //register all tables orm.RegisterModel(new(Deviceinfo), new(Userinfo), new(Admininfo)) //register mysql driver err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } //register default database lte_security err = orm.RegisterDataBase("default", "mysql", "root:way@tcp(192.168.15.155:3306)/lte_security?charset=utf8&loc=Asia%2FShanghai") //orm.RegisterDataBase("default", "mysql", "root:@/lte_security?charset=utf8&loc=Asia%2FShanghai") if err != nil { beego.Critical(err) } }
func init() { err := cbes.RegisterModel(new(License)) if err != nil { beego.Critical(err) } }
func init() { err := cbes.RegisterModel(new(Folder)) if err != nil { beego.Critical(err) } }
func registerDatabase() { beego.Debug(beego.AppConfig.String("elasticsearch::url")) settings := new(cbes.Settings) settings.ElasticSearch.Urls = []string{beego.AppConfig.String("elasticsearch::url")} settings.ElasticSearch.Index = beego.AppConfig.String("elasticsearch::index") settings.ElasticSearch.NumberOfShards = 5 settings.ElasticSearch.NumberOfReplicas = 1 settings.ElasticSearch.RefreshInterval = "10ms" settings.ElasticSearch.CheckOnStartup = true settings.CouchBase.Host = beego.AppConfig.String("couchbase::host") settings.CouchBase.UserName = beego.AppConfig.String("couchbase::username") settings.CouchBase.Pass = beego.AppConfig.String("couchbase::password") bucket := new(cbes.Bucket) bucket.Name = beego.AppConfig.String("couchbase::bucket") bucket.Pass = "" bucket.OperationTimeout = 5 // seconds settings.CouchBase.Bucket = bucket viewsOptions := new(cbes.ViewsOptions) viewsOptions.UpdateInterval = 5000 viewsOptions.UpdateMinChanges = 5 viewsOptions.ReplicaUpdateMinChanges = 5 settings.CouchBase.ViewsOptions = viewsOptions err := cbes.RegisterDataBase(settings) if err != nil { beego.Critical(err) } }
func init() { err := cbes.RegisterModel(new(SecurityGroup)) if err != nil { beego.Critical(err) } }
//数据库连接 func Connect() { var dns string db_type := beego.AppConfig.String("db_type") db_host := beego.AppConfig.String("db_host") db_port := beego.AppConfig.String("db_port") db_user := beego.AppConfig.String("db_user") db_pass := beego.AppConfig.String("db_pass") db_name := beego.AppConfig.String("db_name") db_path := beego.AppConfig.String("db_path") db_sslmode := beego.AppConfig.String("db_sslmode") switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DR_MySQL) dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) break case "postgres": orm.RegisterDriver("postgres", orm.DR_Postgres) dns = fmt.Sprintf("dbname=%s host=%s user=%s password=%s port=%s sslmode=%s", db_name, db_host, db_user, db_pass, db_port, db_sslmode) case "sqlite3": orm.RegisterDriver("sqlite3", orm.DR_Sqlite) if db_path == "" { db_path = "./" } dns = fmt.Sprintf("%s%s.db", db_path, db_name) break default: beego.Critical("Database driver is not allowed:", db_type) } orm.RegisterDataBase("default", db_type, dns) }
/** * 创建数据库 */ func createdb() { fmt.Printf("run dbport \n") db_type := beego.AppConfig.String("dbdriver") db_host := beego.AppConfig.String("dbhost") db_port := beego.AppConfig.String("dbport") db_user := beego.AppConfig.String("dbuser") db_pass := beego.AppConfig.String("dbpass") db_name := beego.AppConfig.String("dbname") var dns string var sqlstring string switch db_type { case "mysql": dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=utf8", db_user, db_pass, db_host, db_port) sqlstring = fmt.Sprintf("CREATE DATABASE if not exists `%s` CHARSET utf8 COLLATE utf8_general_ci", db_name) break default: beego.Critical("Database driver is not allowed:", db_type) } db, err := sql.Open(db_type, dns) if err != nil { panic(err.Error()) } r, err := db.Exec(sqlstring) if err != nil { log.Println(err) log.Println(r) } else { log.Println("Database ", db_name, " created") } defer db.Close() }
func initMaps() { if !com.IsFile(_NAV_TREE_PATH) { beego.Critical(_NAV_TREE_PATH, "does not exist") return } initDocMap() initBlogMap() }
func init() { orm.RegisterModel(new(Userinfo), new(Admininfo), new(Deviceinfo)) err := orm.RegisterDriver("mysql", orm.DR_MySQL) if err != nil { beego.Critical(err) } dbIp := beego.AppConfig.String("DbIp") dbPort := beego.AppConfig.String("DbPort") dbName := beego.AppConfig.String("DbName") dbUser := beego.AppConfig.String("DbUser") dbPassword := beego.AppConfig.String("DbPassword") dbUrl := dbUser + ":" + dbPassword + "@tcp(" + dbIp + ":" + dbPort + ")/" + dbName + "?charset=utf8&loc=Asia%2FShanghai" beego.Debug("dbUrl=", dbUrl) err = orm.RegisterDataBase("default", "mysql", dbUrl) if err != nil { beego.Critical(err) } }
//连接数据库 func ConnectDB() { db_type := beego.AppConfig.String("db::type") db_host := beego.AppConfig.String("db::host") db_port := beego.AppConfig.String("db::port") db_user := beego.AppConfig.String("db::user") db_pass := beego.AppConfig.String("db::pass") db_name := beego.AppConfig.String("db::name") db_path := beego.AppConfig.String("db::path") db_sslmode := beego.AppConfig.String("db::sslmode") var dsn string switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DR_MySQL) dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) dsn += "&loc=Asia%2FShanghai" break case "postgres": orm.RegisterDriver("postgres", orm.DR_Postgres) dsn = fmt.Sprintf("dbname=%s host=%s user=%s password=%s port=%s sslmode=%s", db_name, db_host, db_user, db_pass, db_port, db_sslmode) case "sqlite3": orm.RegisterDriver("sqlite3", orm.DR_Sqlite) if db_path == "" { db_path = "./" } dsn = fmt.Sprintf("%s%s.db", db_path, db_name) break default: beego.Critical("Database driver not support: ", db_type) } orm.RegisterDataBase("default", db_type, dsn) //打印查询日志 orm.Debug, _ = beego.AppConfig.Bool("db::orm_debug") o = orm.NewOrm() // 数据库别名 name := "default" // 不强制重新建数据库 force := false // 打印执行过程 verbose := true // 遇到错误立即返回 err := orm.RunSyncdb(name, force, verbose) if err != nil { beego.Error(err) } }
func main() { //Open orm debug mode orm.Debug = false //Auto create tables err := orm.RunSyncdb("default", false, true) if err != nil { beego.Critical("sycndb error! Error:", err) } //Start app beego.Trace("LTE_Security start running...") beego.Run() }
func init() { appDataDb, err := leveldb.OpenFile(Configs["conf/db.conf"].String("app::path"), nil) if err != nil { beego.Critical("unable to open " + Configs["conf/db.conf"].String("app::path")) } defer appDataDb.Close() urlCountStr, err := appDataDb.Get([]byte("urlCount"), nil) if err != nil { urlCount = int64(1014) } else { urlCount, _ = strconv.ParseInt(string(urlCountStr), 10, 64) } }
//创建数据库 func createDB() { db_type := beego.AppConfig.String("db::type") db_host := beego.AppConfig.String("db::host") db_port := beego.AppConfig.String("db::port") db_user := beego.AppConfig.String("db::user") db_pass := beego.AppConfig.String("db::pass") db_name := beego.AppConfig.String("db::name") db_path := beego.AppConfig.String("db::path") db_sslmode := beego.AppConfig.String("db::sslmode") var dsn string var sqlstring string switch db_type { case "mysql": dsn = fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=utf8&loc=Asia%2FShanghai", db_user, db_pass, db_host, db_port) dsn += "&loc=Asia%2FShanghai" sqlstring = fmt.Sprintf("CREATE DATABASE if not exists `%s` CHARSET utf8 COLLATE utf8_general_ci", db_name) break case "postgres": dsn = fmt.Sprintf("host=%s user=%s password=%s port=%s sslmode=%s", db_host, db_user, db_pass, db_port, db_sslmode) sqlstring = fmt.Sprintf("CREATE DATABASE %s", db_name) break case "sqlite3": if db_path == "" { db_path = "./" } dsn = fmt.Sprintf("%s%s.db", db_path, db_name) os.Remove(dsn) sqlstring = "create table init (n varchar(32));drop table init;" break default: beego.Critical("Database driver not support: ", db_type) } db, err := sql.Open(db_type, dsn) defer db.Close() if err != nil { panic(err.Error()) } r, err := db.Exec(sqlstring) if err != nil { log.Println(err) log.Println(r) } else { log.Println("Database ", db_name, " created") } }
func init() { //获取当天时间 now := time.Now().Format("2006-01-02") file, err := os.OpenFile("/Users/mac/mygo/src/blog/log/"+now+".log", os.O_RDWR|os.O_APPEND, 0644) if err != nil { fd, err := os.Create("/Users/mac/mygo/src/blog/log/" + now + ".log") if err != nil { beego.Critical("openfile beepkg.log:", err) return } lg := log.New(fd, "", log.Ldate|log.Ltime) beego.SetLogger(lg) } lg := log.New(file, "", log.Ldate|log.Ltime) beego.SetLogger(lg) }
//创建数据库 func createDB() { db_type := beego.AppConfig.String("db.type") db_host := beego.AppConfig.String("db.host") db_port := beego.AppConfig.String("db.port") db_user := beego.AppConfig.String("db.user") db_pass := beego.AppConfig.String("db.password") db_name := beego.AppConfig.String("db.name") db_path := beego.AppConfig.String("db.path") db_sslmode := beego.AppConfig.String("db.sslmode") var dns string var sqlstring string switch db_type { case "mysql": dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=utf8", db_user, db_pass, db_host, db_port) sqlstring = fmt.Sprintf("CREATE DATABASE if not exists `%s` CHARSET utf8 COLLATE utf8_general_ci", db_name) break case "postgres": dns = fmt.Sprintf("host=%s user=%s password=%s port=%s sslmode=%s", db_host, db_user, db_pass, db_port, db_sslmode) sqlstring = fmt.Sprintf("CREATE DATABASE %s", db_name) break // case "sqlite3": // if db_path == "" { // db_path = "./" // } // dns = fmt.Sprintf("%s%s.db", db_path, db_name) // os.Remove(dns) // sqlstring = "create table init (n varchar(32));drop table init;" // break default: beego.Critical("Database driver is not allowed:", db_type) } db, err := sql.Open(db_type, dns) if err != nil { panic(err.Error()) } r, err := db.Exec(sqlstring) if err != nil { log.Println(err) log.Println(r) } else { log.Println("Database ", db_name, " created") } defer db.Close() }
func init() { for i := int64(62); i <= maxInt64+1; i *= 62 { pow62s = append(pow62s, i) } base62Indices = make(map[byte]int64) for i := len(base62Candidates) - 1; i >= 0; i-- { base62Indices[byte(base62Candidates[i])] = int64(i) } Configs = make(map[string]config.ConfigContainer) if cf, err := config.NewConfig("ini", "conf/db.conf"); err == nil { Configs["conf/db.conf"] = cf } else { beego.Critical("unable to open conf/db.conf") } }
func init() { runtime.GOMAXPROCS(runtime.NumCPU()) // Set App version and log level. if beego.AppConfig.String("runmode") == "pro" { beego.SetLevel(beego.LevelInfo) beego.Info("Beego Web", APP_VER) os.Mkdir("./log", os.ModePerm) filew := beego.NewFileWriter("log/log", true) err := filew.StartLogger() if err != nil { beego.Critical("NewFileWriter ->", err) } } }
func main() { //开启调试模式 orm.Debug = true //自动同步数据库表格 err := orm.RunSyncdb("default", false, true) if err != nil { beego.Critical("sycndb error! Error:", err) } //开启defer panic支持 //deferstats.NewClient("kxHlEw0EeO5OQj4GNqIG58jsE81p2356") //启动服务 beego.Trace("LMS start running...") beego.Run() }
//数据库连接 func Connect() { var dns string db_type := beego.AppConfig.String("dbdriver") db_host := beego.AppConfig.String("dbhost") db_port := beego.AppConfig.String("dbport") db_user := beego.AppConfig.String("dbuser") db_pass := beego.AppConfig.String("dbpass") db_name := beego.AppConfig.String("dbname") switch db_type { case "mysql": orm.RegisterDriver("mysql", orm.DR_MySQL) dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name) break default: beego.Critical("Database driver is not allowed:", db_type) } orm.RegisterDataBase("default", db_type, dns) }
func init() { runtime.GOMAXPROCS(runtime.NumCPU()) beego.SessionOn = true beego.SessionName = "BTCSport" beego.HttpPort = 8080 os.Mkdir("./log", os.ModePerm) fw := beego.NewFileWriter("./log/log", true) fw.SetRotateMaxDays(30) fw.SetRotateSize(1 << 25) err := fw.StartLogger() if err != nil { beego.Critical("NewFileWriter ->", err) } beego.EnableXSRF = true beego.XSRFKEY = "WO@ilws1314" beego.XSRFExpire = 300 }
func init() { // Try to have highest performance. runtime.GOMAXPROCS(runtime.NumCPU()) // Set application log level. if beego.AppConfig.String("runmode") == "pro" { beego.SetLevel(beego.LevelInfo) } beego.Info("Go Walker", VERSION) // ----- Initialize log file ----- os.Mkdir("./log", os.ModePerm) filew := beego.NewFileWriter("log/log.log", true) err := filew.StartLogger() if err != nil { beego.Critical("NewFileWriter ->", err) } doc.SetGithubCredentials(beego.AppConfig.String("client_id"), beego.AppConfig.String("client_secret")) }
func GetNoteEntryByUrl(url string) (*NoteEntry, error) { urlDb, err := leveldb.OpenFile(Configs["conf/db.conf"].String("url::path"), nil) if err != nil { beego.Critical("unable to open " + Configs["conf/db.conf"].String("url::path")) return nil, errors.New("unable to open database") } defer urlDb.Close() if buf, err := urlDb.Get([]byte(url), nil); err != nil { return nil, err } else { ne := &JsonNoteEntry{} if err := json.Unmarshal(buf, &ne); err != nil { beego.Error("unable to unmarshal" + string(buf)) return nil, errors.New("unable to unmarshal") } else { return ne.toPrivate(), nil } } return nil, nil }
func init() { runtime.GOMAXPROCS(runtime.NumCPU()) // Set App version and log level. routers.AppVer = "v" + APP_VER if beego.AppConfig.String("runmode") == "pro" { beego.SetLevel(beego.LevelInfo) beego.Info("Go Walker Server", APP_VER) os.Mkdir("../log", os.ModePerm) fw := beego.NewFileWriter("../log/log", true) err := fw.StartLogger() if err != nil { beego.Critical("NewFileWriter ->", err) } } doc.SetGithubCredentials(utils.Cfg.MustValue("github", "client_id"), utils.Cfg.MustValue("github", "client_secret")) }
func initDocMap() { if !com.IsFile(_NAV_TREE_PATH) { beego.Critical(_NAV_TREE_PATH, "does not exist") return } // Load navTree.json fn, err := os.Open(_NAV_TREE_PATH) if err != nil { beego.Error("models.init -> load navTree.json:", err.Error()) return } defer fn.Close() d := json.NewDecoder(fn) err = d.Decode(&navTree) if err != nil { beego.Error("models.init -> decode navTree.json:", err.Error()) return } // Documentation names. docNames := make([]string, 0, 20) // Generate usable TplTree for template. TplTree.Sections = make([]Section, len(navTree.Tree)) for i, sec := range navTree.Tree { TplTree.Sections[i].Name = sec.Name TplTree.Sections[i].Nodes = make([]node, len(sec.Nodes)) for j, nod := range sec.Nodes { TplTree.Sections[i].Nodes[j].Index = j + 1 TplTree.Sections[i].Nodes[j].Name = nod docName := sec.Name + "_" + nod TplTree.Sections[i].Nodes[j].FullName = docName docNames = append(docNames, docName) } } docNames = append(docNames, strings.Split( Cfg.MustValue("app", "doc_names"), "|")...) isConfExist := com.IsFile("conf/docTree.json") if isConfExist { f, err := os.Open("conf/docTree.json") if err != nil { beego.Error("models.init -> load data:", err.Error()) return } defer f.Close() d := json.NewDecoder(f) err = d.Decode(&docTree) if err != nil { beego.Error("models.init -> decode data:", err.Error()) return } } else { // Generate 'docTree'. for _, v := range docNames { docTree.Tree = append(docTree.Tree, docNode{Path: v}) } } docLock.Lock() defer docLock.Unlock() docMap = make(map[string]*docFile) langs := strings.Split(Cfg.MustValue("lang", "types"), "|") os.Mkdir("docs", os.ModePerm) for _, l := range langs { os.Mkdir("docs/"+l, os.ModePerm) for _, v := range docTree.Tree { var fullName string if isConfExist { fullName = v.Path } else { fullName = l + "/" + v.Path } docMap[fullName] = getDoc(fullName) } } }
func Critical(message string) { beego.Critical(message) Log.logger.Critical(message) }