提交 1f5edd3a 编写于 作者: G Granty1

Refine some structs and handle cycle import

上级 2abf4013
......@@ -37,7 +37,7 @@
"log": {
"prefix": "[GIN-VUE-ADMIN]",
"logFile": false,
"stdout": ["DEBUG"],
"file": ["WARNING"]
"stdout": "DEBUG",
"file": "WARNING"
}
}
\ No newline at end of file
package init
package config
import (
"fmt"
"gin-vue-admin/global"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Config struct {
MysqlAdmin MysqlAdmin `json:"mysqlAdmin"`
Qiniu Qiniu `json:"qiniu"`
CasbinConfig CasbinConfig `json:"casbinConfig"`
RedisAdmin RedisAdmin `json:"redisAdmin"`
System System `json:"system"`
JWT JWT `json:"jwt"`
Captcha Captcha `json:"captcha"`
Log Log `json:"log"`
type Server struct {
Mysql Mysql `json:"mysql"`
Qiniu Qiniu `json:"qiniu"`
Casbin Casbin `json:"casbin"`
Redis Redis `json:"redis"`
System System `json:"system"`
JWT JWT `json:"jwt"`
Captcha Captcha `json:"captcha"`
Log Log `json:"log"`
}
type System struct { // 系统配置
......@@ -28,11 +21,11 @@ type JWT struct { // jwt签名
SigningKey string `json:"signingKey"`
}
type CasbinConfig struct { //casbin配置
type Casbin struct { //casbin配置
ModelPath string `json:"modelPath"` // casbin model地址配置
}
type MysqlAdmin struct { // mysql admin 数据库配置
type Mysql struct { // mysql admin 数据库配置
Username string `json:"username"`
Password string `json:"password"`
Path string `json:"path"`
......@@ -43,7 +36,7 @@ type MysqlAdmin struct { // mysql admin 数据库配置
LogMode bool `json:"maxOpenConns"`
}
type RedisAdmin struct { // Redis admin 数据库配置
type Redis struct { // Redis admin 数据库配置
Addr string `json:"addr"`
Password string `json:"password"`
DB int `json:"db"`
......@@ -59,45 +52,13 @@ type Captcha struct { // 验证码配置
ImgHeight int `json:"imgHeight"`
}
/**
Log Config
"CRITICAL"
"ERROR"
"WARNING"
"NOTICE"
"INFO"
"DEBUG"
*/
type Log struct {
// log 打印的前缀
Prefix string `json:"prefix"`
// 是否显示打印log的文件具体路径
LogFile bool `json:"logFile"`
// 在控制台打印log的级别, []默认不打印
Stdout []string `json:"stdout"`
// 在文件中打印log的级别 []默认不打印
File []string `json:"file"`
}
func init() {
v := viper.New()
v.SetConfigName("config") // 设置配置文件名 (不带后缀)
v.AddConfigPath("/") // 第一个搜索路径
v.SetConfigType("json")
err := v.ReadInConfig() // 搜索路径,并读取配置数据
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
})
if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
global.GVA_VP = v
// 在控制台打印log的级别, "" 默认不打印
Stdout string `json:"stdout"`
// 在文件中打印log的级别 "" 默认不打印
File string `json:"file"`
}
package core
import (
"fmt"
"gin-vue-admin/global"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
func init() {
v := viper.New()
v.SetConfigName("config") // 设置配置文件名 (不带后缀)
v.AddConfigPath("/") // 第一个搜索路径
v.SetConfigType("json")
err := v.ReadInConfig() // 搜索路径,并读取配置数据
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("config file changed:", e.Name)
if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
})
if err := v.Unmarshal(&global.GVA_CONFIG); err != nil {
fmt.Println(err)
}
global.GVA_VP = v
}
package qmlog
package core
// Register logger
import (
"errors"
"fmt"
"gin-vue-admin/init"
"gin-vue-admin/config"
"gin-vue-admin/global"
"gin-vue-admin/utils"
rotatelogs "github.com/lestrrat/go-file-rotatelogs"
oplogging "github.com/op/go-logging"
......@@ -21,19 +20,13 @@ const (
)
var (
configNotFound = errors.New("logger prefix not found")
defaultFormatter = `%{time:2006/01/02 - 15:04:05.000} %{longfile} %{color:bold}▶ [%{level:.6s}] %{message}%{color:reset}`
)
type Logger struct {
logger *oplogging.Logger
}
func NewLogger() error {
c := init.GinVueAdminconfig.Log
func init() {
c := global.GVA_CONFIG.Log
if c.Prefix == "" {
return configNotFound
_ = fmt.Errorf("logger prefix not found")
}
logger := oplogging.MustGetLogger(module)
var backends []oplogging.Backend
......@@ -41,16 +34,14 @@ func NewLogger() error {
backends = registerFile(c, backends)
oplogging.SetBackend(backends...)
init.SetLogger(logger)
return nil
global.GVA_LOG = logger
}
func registerStdout(c init.Log, backends []oplogging.Backend) []oplogging.Backend {
for _, v := range c.Stdout {
level, err := oplogging.LogLevel(v)
func registerStdout(c config.Log, backends []oplogging.Backend) []oplogging.Backend {
if c.Stdout != "" {
level, err := oplogging.LogLevel(c.Stdout)
if err != nil {
fmt.Println(err)
continue
}
backends = append(backends, createBackend(os.Stdout, c, level))
}
......@@ -58,8 +49,8 @@ func registerStdout(c init.Log, backends []oplogging.Backend) []oplogging.Backen
return backends
}
func registerFile(c init.Log, backends []oplogging.Backend) []oplogging.Backend {
if len(c.File) > 0 {
func registerFile(c config.Log, backends []oplogging.Backend) []oplogging.Backend {
if c.File != "" {
if ok, _ := utils.PathExists(logDir); !ok {
// directory not exist
fmt.Println("create log directory")
......@@ -79,20 +70,17 @@ func registerFile(c init.Log, backends []oplogging.Backend) []oplogging.Backend
fmt.Println(err)
return backends
}
for _, v := range c.File {
level, err := oplogging.LogLevel(v)
if err != nil {
fmt.Println(err)
continue
}
backends = append(backends, createBackend(fileWriter, c, level))
level, err := oplogging.LogLevel(c.File)
if err != nil {
fmt.Println(err)
}
backends = append(backends, createBackend(fileWriter, c, level))
}
return backends
}
func createBackend(w io.Writer, c init.Log, level oplogging.Level) oplogging.Backend {
func createBackend(w io.Writer, c config.Log, level oplogging.Level) oplogging.Backend {
backend := oplogging.NewLogBackend(w, c.Prefix, 0)
stdoutWriter := false
if w == os.Stdout {
......@@ -104,7 +92,7 @@ func createBackend(w io.Writer, c init.Log, level oplogging.Level) oplogging.Bac
return backendLeveled
}
func getLogFormatter(c init.Log, stdoutWriter bool) oplogging.Formatter {
func getLogFormatter(c config.Log, stdoutWriter bool) oplogging.Formatter {
pattern := defaultFormatter
if !stdoutWriter {
// Color is only required for console output
......@@ -118,27 +106,3 @@ func getLogFormatter(c init.Log, stdoutWriter bool) oplogging.Formatter {
}
return oplogging.MustStringFormatter(pattern)
}
func (l Logger) Debug(v ...interface{}) {
l.logger.Debug(v)
}
func (l Logger) Info(v ...interface{}) {
l.logger.Info(v)
}
func (l Logger) Warning(v ...interface{}) {
l.logger.Warning(v)
}
func (l Logger) Error(v ...interface{}) {
l.logger.Error(v)
}
func (l Logger) Critical(v ...interface{}) {
l.logger.Critical(v)
}
func (l Logger) Fatal(v ...interface{}) {
l.logger.Fatal(v)
}
......@@ -11,9 +11,9 @@ import (
func RunWindowsServer() {
if global.GVA_CONFIG.System.UseMultipoint {
// 初始化redis服务
init.RegisterRedis()
init.Redis()
}
Router := init.RegisterRouter()
Router := init.Routers()
Router.Static("/form-generator", "./resource/page")
address := fmt.Sprintf(":%d", global.GVA_CONFIG.System.Addr)
s := &http.Server{
......@@ -24,11 +24,11 @@ func RunWindowsServer() {
MaxHeaderBytes: 1 << 20,
}
time.Sleep(10 * time.Microsecond)
init.L.Debug("server run success on ", address)
global.GVA_LOG.Debug("server run success on ", address)
fmt.Printf(`欢迎使用 Gin-Vue-Admin
默认自动化文档地址:http://127.0.0.1%s/swagger/index.html
默认前端文件运行地址:http://127.0.0.1:8080
`, s.Addr)
init.L.Error(s.ListenAndServe())
global.GVA_LOG.Error(s.ListenAndServe())
}
package global
import (
"gin-vue-admin/init"
"gin-vue-admin/config"
"github.com/go-redis/redis"
"github.com/jinzhu/gorm"
oplogging "github.com/op/go-logging"
"github.com/spf13/viper"
)
var (
GVA_DB *gorm.DB
GVA_REDIS *redis.Client
GVA_LOG init.Logger
GVA_CONFIG init.Config
GVA_CONFIG config.Server
GVA_VP *viper.Viper
GVA_LOG *oplogging.Logger
)
package init
import (
"gin-vue-admin/global"
"gin-vue-admin/model"
"github.com/jinzhu/gorm"
)
//注册数据库表专用
func RegisterTable(db *gorm.DB) {
func DBTables() {
db := global.GVA_DB
db.AutoMigrate(model.SysUser{},
model.SysAuthority{},
model.SysMenu{},
......@@ -20,5 +21,5 @@ func RegisterTable(db *gorm.DB) {
model.ExaFileChunk{},
model.ExaCustomer{},
)
L.Debug("register table success")
global.GVA_LOG.Debug("register table success")
}
package init
// Custom Logger
type Logger interface {
Debug(v ...interface{})
Info(v ...interface{})
Warning(v ...interface{})
Error(v ...interface{})
Critical(v ...interface{})
Fatal(v ...interface{})
}
var L Logger
func SetLogger(logger Logger) {
L = logger
}
......@@ -7,9 +7,10 @@ import (
)
//初始化数据库并产生数据库全局变量
func RegisterMysql(admin MysqlAdmin) {
func Mysql() {
admin := global.GVA_CONFIG.MysqlAdmin
if db, err := gorm.Open("mysql", admin.Username+":"+admin.Password+"@("+admin.Path+")/"+admin.Dbname+"?"+admin.Config); err != nil {
L.Error("DEFAULTDB数据库启动异常", err)
global.GVA_LOG.Error("DEFAULTDB数据库启动异常", err)
} else {
global.GVA_DB = db
global.GVA_DB.DB().SetMaxIdleConns(admin.MaxIdleConns)
......
......@@ -5,17 +5,18 @@ import (
"github.com/go-redis/redis"
)
func RegisterRedis() {
func Redis() {
redisCfg := global.GVA_CONFIG.RedisAdmin
client := redis.NewClient(&redis.Options{
Addr: GinVueAdminconfig.RedisAdmin.Addr,
Password: GinVueAdminconfig.RedisAdmin.Password, // no password set
DB: GinVueAdminconfig.RedisAdmin.DB, // use default DB
Addr: redisCfg.Addr,
Password: redisCfg.Password, // no password set
DB: redisCfg.DB, // use default DB
})
pong, err := client.Ping().Result()
if err != nil {
L.Error(err)
global.GVA_LOG.Error(err)
} else {
L.Info("redis connect ping response:", pong)
global.GVA_LOG.Info("redis connect ping response:", pong)
global.GVA_REDIS = client
}
}
......@@ -2,6 +2,7 @@ package init
import (
_ "gin-vue-admin/docs"
"gin-vue-admin/global"
"gin-vue-admin/middleware"
"gin-vue-admin/router"
"github.com/gin-gonic/gin"
......@@ -10,18 +11,16 @@ import (
)
//初始化总路由
func RegisterRouter() *gin.Engine {
func Routers() *gin.Engine {
var Router = gin.Default()
//Router.Use(middleware.LoadTls()) // 打开就能玩https了
// 如果不需要日志 请关闭这里
Router.Use(middleware.Logger())
L.Debug("use middleware logger")
global.GVA_LOG.Debug("use middleware logger")
// 跨域
Router.Use(middleware.Cors())
L.Debug("use middleware cors")
global.GVA_LOG.Debug("use middleware cors")
Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
L.Debug("register swagger handler")
global.GVA_LOG.Debug("register swagger handler")
// 方便统一添加路由组前缀 多服务器上线使用
ApiGroup := Router.Group("")
router.InitUserRouter(ApiGroup) // 注册用户路由
......
......@@ -4,36 +4,12 @@ import (
"gin-vue-admin/core"
"gin-vue-admin/global"
"gin-vue-admin/init"
"gin-vue-admin/init/qmlog"
"os"
//"runtime"
)
// @title Swagger Example API
// @version 0.0.1
// @description This is a sample Server pets
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name x-token
// @BasePath /
var (
mysqlHost = os.Getenv("MYSQLHOST")
mysqlPort = os.Getenv("MYSQLPORT")
)
func main() {
if err := qmlog.NewLogger(); err != nil {
panic(err)
}
// 可以通过环境变量来覆盖配置值
// 未设定有效的环境变量时,使用配置值
mysqlConfig := init.GinVueAdminconfig.MysqlAdmin
// 链接初始化数据库
init.RegisterMysql(mysqlConfig) // 链接初始化数据库
// 注册数据库表
init.RegisterTable(global.GVA_DB)
init.Mysql()
init.DBTables()
// 程序结束前关闭数据库链接
defer global.GVA_DB.Close()
......
package middleware
import (
"bytes"
"gin-vue-admin/init"
"net/http/httputil"
"strings"
"time"
"github.com/gin-gonic/gin"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
// request time
start := time.Now()
// request path
path := c.Request.URL.Path
logFlag := true
if strings.Contains(path, "swagger") {
logFlag = false
}
// request ip
clientIP := c.ClientIP()
// method
method := c.Request.Method
// copy request content
req, _ := httputil.DumpRequest(c.Request, true)
if logFlag {
init.L.Debug(
"Request:", method, clientIP, path, string(req))
}
// replace writer
cusWriter := &responseBodyWriter{
ResponseWriter: c.Writer,
body: bytes.NewBufferString(""),
}
c.Writer = cusWriter
// handle request
c.Next()
// ending time
end := time.Now()
//execute time
latency := end.Sub(start)
statusCode := c.Writer.Status()
if logFlag {
init.L.Debug(
"Response:",
statusCode,
latency,
cusWriter.body.String())
}
}
}
type responseBodyWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w responseBodyWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
package model
import (
"gin-vue-admin/config"
"gin-vue-admin/global"
"gin-vue-admin/init"
"gin-vue-admin/utils"
)
//配置文件结构体
type System struct {
Config init.Config
Config config.Server
}
//读取配置文件
func (s *System) GetSystemConfig() (err error, conf init.Config) {
func (s *System) GetSystemConfig() (err error, conf config.Server) {
return nil, global.GVA_CONFIG
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册