Keep refine the structure.

This commit is contained in:
zicla 2019-04-26 02:38:53 +08:00
parent b3c52ea50e
commit 8edc30babc
11 changed files with 56 additions and 50 deletions

View File

@ -7,14 +7,14 @@ import (
"net/http" "net/http"
"tank/rest" "tank/rest"
"tank/rest/config" "tank/rest/config"
"tank/rest/tool" "tank/rest/logger"
) )
func main() { func main() {
//日志第一优先级保障 //日志第一优先级保障
tool.LOGGER.Init() logger.LOGGER.Init()
defer tool.LOGGER.Destroy() defer logger.LOGGER.Destroy()
//装载配置文件,这个决定了是否需要执行安装过程 //装载配置文件,这个决定了是否需要执行安装过程
config.CONFIG.Init() config.CONFIG.Init()
@ -25,7 +25,7 @@ func main() {
http.Handle("/", rest.CONTEXT.Router) http.Handle("/", rest.CONTEXT.Router)
tool.LOGGER.Info("App started at http://localhost:%v", config.CONFIG.ServerPort) logger.LOGGER.Info("App started at http://localhost:%v", config.CONFIG.ServerPort)
dotPort := fmt.Sprintf(":%v", config.CONFIG.ServerPort) dotPort := fmt.Sprintf(":%v", config.CONFIG.ServerPort)
err1 := http.ListenAndServe(dotPort, nil) err1 := http.ListenAndServe(dotPort, nil)

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"tank/rest/config" "tank/rest/config"
"tank/rest/logger"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool" "tank/rest/tool"
) )
@ -20,11 +21,11 @@ type IBean interface {
} }
type Bean struct { type Bean struct {
logger *tool.Logger logger *logger.Logger
} }
func (this *Bean) Init() { func (this *Bean) Init() {
this.logger = tool.LOGGER this.logger = logger.LOGGER
} }
func (this *Bean) ConfigPost() { func (this *Bean) ConfigPost() {

View File

@ -1,10 +1,11 @@
package tool package cache
import ( import (
"errors" "errors"
"fmt" "fmt"
"sort" "sort"
"sync" "sync"
"tank/rest/tool"
"time" "time"
) )
@ -196,7 +197,7 @@ func (table *CacheTable) checkExpire() {
table.cleanupInterval = smallestDuration table.cleanupInterval = smallestDuration
if smallestDuration > 0 { if smallestDuration > 0 {
table.cleanupTimer = time.AfterFunc(smallestDuration, func() { table.cleanupTimer = time.AfterFunc(smallestDuration, func() {
go SafeMethod(table.checkExpire) go tool.SafeMethod(table.checkExpire)
}) })
} }
table.Unlock() table.Unlock()

View File

@ -3,6 +3,7 @@ package config
import ( import (
"github.com/json-iterator/go" "github.com/json-iterator/go"
"io/ioutil" "io/ioutil"
"tank/rest/logger"
"tank/rest/tool" "tank/rest/tool"
"time" "time"
"unsafe" "unsafe"
@ -65,7 +66,7 @@ type ConfigItem struct {
func (this *ConfigItem) validate() bool { func (this *ConfigItem) validate() bool {
if this.ServerPort == 0 { if this.ServerPort == 0 {
tool.LOGGER.Error("ServerPort 未配置") logger.LOGGER.Error("ServerPort 未配置")
return false return false
} else { } else {
//只要配置文件中有配置端口,就使用。 //只要配置文件中有配置端口,就使用。
@ -73,27 +74,27 @@ func (this *ConfigItem) validate() bool {
} }
if this.MysqlUsername == "" { if this.MysqlUsername == "" {
tool.LOGGER.Error("MysqlUsername 未配置") logger.LOGGER.Error("MysqlUsername 未配置")
return false return false
} }
if this.MysqlPassword == "" { if this.MysqlPassword == "" {
tool.LOGGER.Error("MysqlPassword 未配置") logger.LOGGER.Error("MysqlPassword 未配置")
return false return false
} }
if this.MysqlHost == "" { if this.MysqlHost == "" {
tool.LOGGER.Error("MysqlHost 未配置") logger.LOGGER.Error("MysqlHost 未配置")
return false return false
} }
if this.MysqlPort == 0 { if this.MysqlPort == 0 {
tool.LOGGER.Error("MysqlPort 未配置") logger.LOGGER.Error("MysqlPort 未配置")
return false return false
} }
if this.MysqlSchema == "" { if this.MysqlSchema == "" {
tool.LOGGER.Error("MysqlSchema 未配置") logger.LOGGER.Error("MysqlSchema 未配置")
return false return false
} }
@ -135,14 +136,14 @@ func (this *Config) ReadFromConfigFile() {
filePath := tool.GetConfPath() + "/tank.json" filePath := tool.GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath) content, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
tool.LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath) logger.LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath)
this.Installed = false this.Installed = false
} else { } else {
this.Item = &ConfigItem{} this.Item = &ConfigItem{}
tool.LOGGER.Warn("读取配置文件:%s", filePath) logger.LOGGER.Warn("读取配置文件:%s", filePath)
err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item) err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item)
if err != nil { if err != nil {
tool.LOGGER.Error("配置文件格式错误! 即将进入安装过程!") logger.LOGGER.Error("配置文件格式错误! 即将进入安装过程!")
this.Installed = false this.Installed = false
return return
} }
@ -150,7 +151,7 @@ func (this *Config) ReadFromConfigFile() {
//验证项是否齐全 //验证项是否齐全
itemValidate := this.Item.validate() itemValidate := this.Item.validate()
if !itemValidate { if !itemValidate {
tool.LOGGER.Error("配置文件信息不齐全! 即将进入安装过程!") logger.LOGGER.Error("配置文件信息不齐全! 即将进入安装过程!")
this.Installed = false this.Installed = false
return return
} }
@ -171,8 +172,8 @@ func (this *Config) ReadFromConfigFile() {
this.MysqlUrl = tool.GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword) this.MysqlUrl = tool.GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword)
this.Installed = true this.Installed = true
tool.LOGGER.Info("使用配置文件:%s", filePath) logger.LOGGER.Info("使用配置文件:%s", filePath)
tool.LOGGER.Info("上传文件存放路径:%s", this.MatterPath) logger.LOGGER.Info("上传文件存放路径:%s", this.MatterPath)
} }
} }

View File

@ -4,8 +4,9 @@ import (
"fmt" "fmt"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"reflect" "reflect"
"tank/rest/cache"
"tank/rest/config" "tank/rest/config"
"tank/rest/tool" "tank/rest/logger"
) )
//全局唯一的上下文(在main函数中初始化) //全局唯一的上下文(在main函数中初始化)
@ -16,7 +17,7 @@ type Context struct {
//数据库连接 //数据库连接
DB *gorm.DB DB *gorm.DB
//session缓存 //session缓存
SessionCache *tool.CacheTable SessionCache *cache.CacheTable
//各类的Bean Map。这里面是包含ControllerMap中所有元素 //各类的Bean Map。这里面是包含ControllerMap中所有元素
BeanMap map[string]IBean BeanMap map[string]IBean
//只包含了Controller的map //只包含了Controller的map
@ -29,7 +30,7 @@ type Context struct {
func (this *Context) Init() { func (this *Context) Init() {
//创建一个用于存储session的缓存。 //创建一个用于存储session的缓存。
this.SessionCache = tool.NewCacheTable() this.SessionCache = cache.NewCacheTable()
//初始化Map //初始化Map
this.BeanMap = make(map[string]IBean) this.BeanMap = make(map[string]IBean)
@ -55,7 +56,7 @@ func (this *Context) OpenDb() {
this.DB, err = gorm.Open("mysql", config.CONFIG.MysqlUrl) this.DB, err = gorm.Open("mysql", config.CONFIG.MysqlUrl)
if err != nil { if err != nil {
tool.LOGGER.Panic("failed to connect mysql database") logger.LOGGER.Panic("failed to connect mysql database")
} }
//是否打开sql日志(在调试阶段可以打开以方便查看执行的SQL) //是否打开sql日志(在调试阶段可以打开以方便查看执行的SQL)
@ -82,7 +83,7 @@ func (this *Context) registerBean(bean IBean) {
err := fmt.Sprintf("【%s】已经被注册了跳过。", typeName) err := fmt.Sprintf("【%s】已经被注册了跳过。", typeName)
if _, ok := this.BeanMap[typeName]; ok { if _, ok := this.BeanMap[typeName]; ok {
tool.LOGGER.Error(fmt.Sprintf(err)) logger.LOGGER.Error(fmt.Sprintf(err))
} else { } else {
this.BeanMap[typeName] = element this.BeanMap[typeName] = element
@ -94,7 +95,7 @@ func (this *Context) registerBean(bean IBean) {
} }
} else { } else {
tool.LOGGER.Panic("注册的【%s】不是Bean类型。", typeName) logger.LOGGER.Panic("注册的【%s】不是Bean类型。", typeName)
} }
} }
@ -164,7 +165,7 @@ func (this *Context) GetBean(bean IBean) IBean {
if val, ok := this.BeanMap[typeName]; ok { if val, ok := this.BeanMap[typeName]; ok {
return val return val
} else { } else {
tool.LOGGER.Panic("【%s】没有注册。", typeName) logger.LOGGER.Panic("【%s】没有注册。", typeName)
return nil return nil
} }
} }

View File

@ -1,4 +1,4 @@
package tool package download
import ( import (
"errors" "errors"
@ -12,6 +12,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
"time" "time"
) )
@ -265,7 +266,7 @@ func DownloadFile(
var ctype string var ctype string
if !haveType { if !haveType {
//使用mimeUtil来获取mime //使用mimeUtil来获取mime
ctype = GetFallbackMimeType(filename, "") ctype = tool.GetFallbackMimeType(filename, "")
if ctype == "" { if ctype == "" {
// read a chunk to decide between utf-8 text and binary // read a chunk to decide between utf-8 text and binary
var buf [sniffLen]byte var buf [sniffLen]byte

View File

@ -1,4 +1,4 @@
package tool package logger
import ( import (
"fmt" "fmt"
@ -6,6 +6,7 @@ import (
"os" "os"
"runtime" "runtime"
"sync" "sync"
"tank/rest/tool"
"time" "time"
) )
@ -38,7 +39,7 @@ func (this *Logger) log(prefix string, format string, v ...interface{}) {
line = 0 line = 0
} }
var consoleFormat = fmt.Sprintf("%s%s %s:%d %s", prefix, ConvertTimeToTimeString(time.Now()), GetFilenameOfPath(file), line, content) var consoleFormat = fmt.Sprintf("%s%s %s:%d %s", prefix, tool.ConvertTimeToTimeString(time.Now()), tool.GetFilenameOfPath(file), line, content)
fmt.Printf(consoleFormat) fmt.Printf(consoleFormat)
this.goLogger.SetPrefix(prefix) this.goLogger.SetPrefix(prefix)
@ -77,12 +78,12 @@ func (this *Logger) Init() {
this.openFile() this.openFile()
//日志需要自我备份,自我维护。明天第一秒触发 //日志需要自我备份,自我维护。明天第一秒触发
nextTime := FirstSecondOfDay(Tomorrow()) nextTime := tool.FirstSecondOfDay(tool.Tomorrow())
duration := nextTime.Sub(time.Now()) duration := nextTime.Sub(time.Now())
this.Info("下一次日志维护时间%s 距当前 %ds ", ConvertTimeToDateTimeString(nextTime), duration/time.Second) this.Info("下一次日志维护时间%s 距当前 %ds ", tool.ConvertTimeToDateTimeString(nextTime), duration/time.Second)
this.maintainTimer = time.AfterFunc(duration, func() { this.maintainTimer = time.AfterFunc(duration, func() {
go SafeMethod(this.maintain) go tool.SafeMethod(this.maintain)
}) })
} }
@ -99,7 +100,7 @@ func (this *Logger) maintain() {
this.closeFile() this.closeFile()
//日志归类到昨天 //日志归类到昨天
destPath := GetLogPath() + "/tank-" + Yesterday().Local().Format("2006-01-02") + ".log" destPath := tool.GetLogPath() + "/tank-" + tool.Yesterday().Local().Format("2006-01-02") + ".log"
//直接重命名文件 //直接重命名文件
err := os.Rename(this.fileName(), destPath) err := os.Rename(this.fileName(), destPath)
@ -112,17 +113,17 @@ func (this *Logger) maintain() {
//准备好下次维护日志的时间。 //准备好下次维护日志的时间。
now := time.Now() now := time.Now()
nextTime := FirstSecondOfDay(Tomorrow()) nextTime := tool.FirstSecondOfDay(tool.Tomorrow())
duration := nextTime.Sub(now) duration := nextTime.Sub(now)
this.Info("下次维护时间:%s ", ConvertTimeToDateTimeString(nextTime)) this.Info("下次维护时间:%s ", tool.ConvertTimeToDateTimeString(nextTime))
this.maintainTimer = time.AfterFunc(duration, func() { this.maintainTimer = time.AfterFunc(duration, func() {
go SafeMethod(this.maintain) go tool.SafeMethod(this.maintain)
}) })
} }
//日志名称 //日志名称
func (this *Logger) fileName() string { func (this *Logger) fileName() string {
return GetLogPath() + "/tank.log" return tool.GetLogPath() + "/tank.log"
} }
//打开日志文件 //打开日志文件

View File

@ -6,6 +6,7 @@ import (
"os" "os"
"regexp" "regexp"
"strings" "strings"
"tank/rest/download"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool" "tank/rest/tool"
) )
@ -64,7 +65,7 @@ func (this *MatterService) DownloadFile(
filename string, filename string,
withContentDisposition bool) { withContentDisposition bool) {
tool.DownloadFile(writer, request, filePath, filename, withContentDisposition) download.DownloadFile(writer, request, filePath, filename, withContentDisposition)
} }
//删除文件 //删除文件

View File

@ -8,6 +8,7 @@ import (
"os" "os"
"strings" "strings"
"tank/rest/config" "tank/rest/config"
"tank/rest/logger"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool" "tank/rest/tool"
"time" "time"
@ -71,7 +72,7 @@ func NewRouter() *Router {
func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http.Request, startTime time.Time) { func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http.Request, startTime time.Time) {
if err := recover(); err != nil { if err := recover(); err != nil {
tool.LOGGER.Error("错误: %v", err) logger.LOGGER.Error("错误: %v", err)
var webResult *result.WebResult = nil var webResult *result.WebResult = nil
if value, ok := err.(string); ok { if value, ok := err.(string); ok {

View File

@ -9,6 +9,7 @@ import (
"os/user" "os/user"
"path/filepath" "path/filepath"
"strings" "strings"
"tank/rest/result"
) )
//判断文件或文件夹是否已经存在 //判断文件或文件夹是否已经存在
@ -125,19 +126,17 @@ func GetFilenameOfPath(fullPath string) string {
func DeleteEmptyDir(dirPath string) bool { func DeleteEmptyDir(dirPath string) bool {
dir, err := ioutil.ReadDir(dirPath) dir, err := ioutil.ReadDir(dirPath)
if err != nil { if err != nil {
LOGGER.Error("尝试读取目录%s时出错 %s", dirPath, err.Error()) panic(result.BadRequest("尝试读取目录%s时出错 %s", dirPath, err.Error()))
panic("尝试读取目录时出错 " + err.Error())
} }
if len(dir) == 0 { if len(dir) == 0 {
//空文件夹 //空文件夹
err = os.Remove(dirPath) err = os.Remove(dirPath)
if err != nil { if err != nil {
LOGGER.Error("删除磁盘上的文件夹%s出错 %s", dirPath, err.Error()) panic(result.BadRequest("删除磁盘上的文件夹%s出错 %s", dirPath, err.Error()))
} }
return true return true
} else {
LOGGER.Info("文件夹不为空,%v", len(dir))
} }
return false return false
} }
@ -215,7 +214,6 @@ func GetLogPath() string {
return filePath return filePath
} }
//复制文件 //复制文件
func CopyFile(srcPath string, destPath string) (nBytes int64) { func CopyFile(srcPath string, destPath string) (nBytes int64) {

View File

@ -2,8 +2,8 @@ package rest
import ( import (
"net/http" "net/http"
"tank/rest/cache"
"tank/rest/config" "tank/rest/config"
"tank/rest/tool"
"time" "time"
) )
@ -14,7 +14,7 @@ type UserService struct {
sessionDao *SessionDao sessionDao *SessionDao
//操作文件的锁。 //操作文件的锁。
locker *tool.CacheTable locker *cache.CacheTable
} }
//初始化方法 //初始化方法
@ -33,7 +33,7 @@ func (this *UserService) Init() {
} }
//创建一个用于存储用户文件锁的缓存。 //创建一个用于存储用户文件锁的缓存。
this.locker = tool.NewCacheTable() this.locker = cache.NewCacheTable()
} }