Esempio n. 1
0
File: models.go Progetto: hzmnet/api
func newEngine(conf setting.DataBaseConfig) (*xorm.Engine, error) {
	cnnstr := ""
	switch conf.TYPE {
	case "mysql":
		if conf.HOST[0] == '/' { // looks like a unix socket
			cnnstr = fmt.Sprintf("%s:%s@unix(%s)/%s?charset=utf8",
				conf.USER, conf.PASSWD, conf.HOST, conf.DB)
		} else {
			cnnstr = fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",
				conf.USER, conf.PASSWD, conf.HOST, conf.DB)
		}
	case "postgres":
		var host, port = "127.0.0.1", "5432"
		fields := strings.Split(conf.HOST, ":")
		if len(fields) > 0 && len(strings.TrimSpace(fields[0])) > 0 {
			host = fields[0]
		}
		if len(fields) > 1 && len(strings.TrimSpace(fields[1])) > 0 {
			port = fields[1]
		}
		cnnstr = fmt.Sprintf("user=%s password=%s host=%s port=%s dbname=%s sslmode=%s",
			conf.USER, conf.PASSWD, host, port, conf.DB, conf.SSL_MODE)
	case "sqlite3":
		os.MkdirAll(path.Dir(conf.PATH), os.ModePerm)
		cnnstr = "file:" + conf.PATH + "?cache=shared&mode=rwc"
	default:
		return nil, fmt.Errorf("Unknown database type: %s", conf.TYPE)
	}
	x, err := xorm.NewEngine(conf.TYPE, cnnstr)
	if err != nil {
		return nil, err
	}
	// 连接池的空闲数大小
	x.SetMaxIdleConns(conf.MaxIdle)
	// 最大打开连接数
	x.SetMaxOpenConns(conf.MaxOpen)

	x.ShowSQL = true
	// 则会在控制台打印出生成的SQL语句;
	x.ShowDebug = true
	// 则会在控制台打印调试信息;
	x.ShowErr = true
	// 则会在控制台打印错误信息;
	x.ShowWarn = true
	// 则会在控制台打印警告信息;

	logpath, _ := filepath.Abs(conf.LogPath)
	os.MkdirAll(path.Dir(logpath), os.ModePerm)
	// 日志
	f, err := os.Create(logpath)
	if err != nil {
		log.Error(4, "create xorm log file failed %v", err)
		return nil, err
	}
	// defer f.Close()
	x.Logger = xorm.NewSimpleLogger(f)
	return x, nil
}
Esempio n. 2
0
File: redis.go Progetto: hzmnet/api
func RedisCheckConn() {
	for name, pool := range RedisPools {
		go func(name string, pool *redis.Pool) {
			log.Debug("check Redis conn name : %s", name)

			conn := pool.Get()
			res, err := conn.Do("PING")
			if err != nil {
				log.Error(4, "redis name %s, conn failed  %v", name, err)
			} else {
				log.Debug("redis name %s, conn ok %v", name, res)
			}
			conn.Close()
		}(name, pool)

	}
}
Esempio n. 3
0
File: models.go Progetto: hzmnet/api
func InitDatabaseConn() {

	if len(setting.Cfg.DBMaster) == 0 || len(setting.Cfg.DBSlave) == 0 {
		panic("setting.Cfg.DBMaster & DBSlave must be set ")
	}

	for name, conf := range setting.Cfg.DBs {
		x, err := newEngine(conf)
		if err != nil {
			log.Error(4, "newEngine failed name %s  %v", name, err)
			continue
		}

		XormEngines[name] = x
	}

	masterPolling = polling.NewPolling(len(setting.Cfg.DBMaster))
	masterPolling = polling.NewPolling(len(setting.Cfg.DBSlave))

	log.Debug("初始化 models done %v", XormEngines)
}
Esempio n. 4
0
func newLogService() {
	f := "logs.toml"
	configPath := getUserConfigFile(f)

	m := multiconfig.NewWithPath(configPath)
	err := m.Load(Cfg)
	if err != nil {
		panic(err)
	}

	for _, conf := range Cfg.Logs {
		if !conf.ENABLE {
			continue
		}
		level, ok := logLevels[conf.LEVEL]
		if !ok {
			log.Fatal(4, "Unknown log level: %s", conf.LEVEL)
		}

		str := ""
		switch conf.MODE {
		case "console":
			str = fmt.Sprintf(`{"level":%s}`, level)
		case "file":
			str = fmt.Sprintf(
				`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`,
				level,
				conf.FILE_NAME,
				conf.LOG_ROTATE,
				conf.MAX_LINES,
				1<<uint(conf.MAX_SIZE_SHIFT),
				conf.DAILY_ROTATE, conf.MAX_DAYS,
			)
		case "conn":
			str = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
				conf.RECONNECT_ON_MSG,
				conf.RECONNECT,
				conf.PROTOCOL,
				conf.ADDR)
		case "smtp":

			tos, err := json.Marshal(conf.RECEIVERS)
			if err != nil {
				log.Error(4, "json.Marshal(conf.RECEIVERS) err %v", err)
				continue
			}

			str = fmt.Sprintf(`{"level":%s,"username":"******","password":"******","host":"%s","sendTos":%s,"subject":"%s"}`, level,
				conf.USER,
				conf.PASSWD,
				conf.HOST,
				tos,
				conf.SUBJECT)
		case "database":
			str = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
				conf.DRIVER,
				conf.CONN)
		default:
			continue
		}

		log.Info(str)
		log.NewLogger(conf.BUFFER_LEN, conf.MODE, str)
		log.Info("Log Mode: %s(%s)", conf.MODE, conf.LEVEL)
	}

}
Esempio n. 5
0
File: log.go Progetto: weisd/api
func InitLogs() {

	LogsMap = make(map[string]loggerMap)

	for name, v := range setting.Cfg.Logs {
		loggerMaper := make(map[string]*baseLog.Logger)
		for _, conf := range v {

			if !conf.ENABLE {
				continue
			}
			level, ok := logLevels[conf.LEVEL]
			if !ok {
				baseLog.Fatal(4, "Unknown log level: %s", conf.LEVEL)
			}

			str := ""
			switch conf.MODE {
			case "console":
				str = fmt.Sprintf(`{"level":%s}`, level)
			case "file":
				str = fmt.Sprintf(
					`{"level":%s,"filename":"%s","rotate":%v,"maxlines":%d,"maxsize":%d,"daily":%v,"maxdays":%d}`,
					level,
					conf.FILE_NAME,
					conf.LOG_ROTATE,
					conf.MAX_LINES,
					1<<uint(conf.MAX_SIZE_SHIFT),
					conf.DAILY_ROTATE, conf.MAX_DAYS,
				)
			case "conn":
				str = fmt.Sprintf(`{"level":%s,"reconnectOnMsg":%v,"reconnect":%v,"net":"%s","addr":"%s"}`, level,
					conf.RECONNECT_ON_MSG,
					conf.RECONNECT,
					conf.PROTOCOL,
					conf.ADDR)
			case "smtp":

				tos, err := json.Marshal(conf.RECEIVERS)
				if err != nil {
					baseLog.Error(4, "json.Marshal(conf.RECEIVERS) err %v", err)
					continue
				}

				str = fmt.Sprintf(`{"level":%s,"username":"******","password":"******","host":"%s","sendTos":%s,"subject":"%s"}`, level,
					conf.USER,
					conf.PASSWD,
					conf.HOST,
					tos,
					conf.SUBJECT)
			case "database":
				str = fmt.Sprintf(`{"level":%s,"driver":"%s","conn":"%s"}`, level,
					conf.DRIVER,
					conf.CONN)
			default:
				continue
			}

			baseLog.Info(str)

			loggerMaper[conf.MODE] = baseLog.NewCustomLogger(conf.BUFFER_LEN, conf.MODE, str)
			baseLog.Info("Log Mode: %s(%s)", conf.MODE, conf.LEVEL)

		}

		LogsMap[name] = loggerMaper
	}

	Info("logs 初始化完成 map %v", LogsMap)

}
Esempio n. 6
0
File: main.go Progetto: hzmnet/api
func main() {
	bootstraps()

	e := echo.New()

	if setting.Cfg.Debug {
		log.Info("SetDebug on")
		e.SetDebug(setting.Cfg.Debug)
	}

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())
	e.Use(cache.EchoCacher(cache.Options{Adapter: "redis", AdapterConfig: `{"Addr":":6379"}`, Section: "test", Interval: 5}))
	e.Use(statistics.Statisticser())
	// 固定返回值
	e.SetHTTPErrorHandler(func(err error, c *echo.Context) {
		code := http.StatusInternalServerError
		msg := http.StatusText(code)
		if he, ok := err.(*echo.HTTPError); ok {
			code = he.Code()
			msg = he.Error()
		}

		if e.Debug() {
			msg = err.Error()
		}

		log.Error(4, "http err  %v", err)

		c.JSON(200, api.ResErr(code, msg))

	})

	// Routes
	e.Get("/", version)
	e.Get("/test/add", func(c *echo.Context) error {
		u := new(user.User)
		u.Name = "weisd"

		act, err := user.Create(u)
		if err != nil {
			return c.JSON(200, api.ResErr(500, err.Error()))
		}

		return c.JSON(200, api.ResOk(act))
	})

	e.Get("/test/stat", func(c *echo.Context) error {
		status := statistics.StatisticsMap.GetMap()
		html := strings.Join(status["Fields"].([]string), " ")
		html += "<br>"
		data := status["Data"].([][]string)
		for i, l := 0, len(data); i < l; i++ {
			html += strings.Join(data[i], " ")
			html += "<br>"
		}

		return c.HTML(200, html)

	})

	e.Get("/test/cache/put", func(c *echo.Context) error {
		err := cache.Store(c).Put("name", "weisd", 10)
		if err != nil {
			return err
		}

		return c.String(200, "store ok")
	})

	e.Get("/test/cache/get", func(c *echo.Context) error {
		name := cache.Store(c).Get("name")

		return c.String(200, "get name %s", name)
	})

	var jwtSigningKeys = map[string]string{"da": "weisd"}

	j := e.Group("/jwt")
	j.Use(jwt.EchoJWTAuther(func(c *echo.Context) (key string, err error) {
		// get the clientId from header
		clientId := c.Request().Header.Get("client-id")
		key, ok := jwtSigningKeys[clientId]
		if !ok {
			return "", echo.NewHTTPError(http.StatusUnauthorized)
		}
		return key, nil
	}))

	j.Get("", func(c *echo.Context) error {
		return c.String(200, "jwt Access ok with claims %v", jwt.Claims(c))
	})

	e.Get("/test/jwt/token", func(c *echo.Context) error {
		claims := map[string]interface{}{"token": "weisd"}
		token, err := jwt.NewToken("weisd", claims)
		if err != nil {
			return err
		}
		// show the token use for test
		return c.String(200, "token : %s", token)
	})

	// Start server
	e.Run(":1323")
}