Rename tool to util.

This commit is contained in:
zicla 2019-04-26 03:01:40 +08:00
parent ce84a9c9f0
commit aed1ee2001
28 changed files with 104 additions and 104 deletions

View File

@ -6,7 +6,7 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -130,7 +130,7 @@ func (this *AlienController) CheckRequestUser(writer http.ResponseWriter, reques
if user == nil { if user == nil {
panic(`邮箱或密码错误`) panic(`邮箱或密码错误`)
} else { } else {
if !tool.MatchBcrypt(password, user.Password) { if !util.MatchBcrypt(password, user.Password) {
panic(`邮箱或密码错误`) panic(`邮箱或密码错误`)
} }
} }
@ -210,7 +210,7 @@ func (this *AlienController) FetchUploadToken(writer http.ResponseWriter, reques
Filename: filename, Filename: filename,
Privacy: privacy, Privacy: privacy,
Size: size, Size: size,
Ip: tool.GetIpAddress(request), Ip: util.GetIpAddress(request),
} }
uploadToken = this.uploadTokenDao.Create(uploadToken) uploadToken = this.uploadTokenDao.Create(uploadToken)
@ -403,7 +403,7 @@ func (this *AlienController) FetchDownloadToken(writer http.ResponseWriter, requ
UserUuid: user.Uuid, UserUuid: user.Uuid,
MatterUuid: matterUuid, MatterUuid: matterUuid,
ExpireTime: time.Now().Add(mm), ExpireTime: time.Now().Add(mm),
Ip: tool.GetIpAddress(request), Ip: util.GetIpAddress(request),
} }
downloadToken = this.downloadTokenDao.Create(downloadToken) downloadToken = this.downloadTokenDao.Create(downloadToken)

View File

@ -4,7 +4,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -134,7 +134,7 @@ func (this *AlienService) PreviewOrDownload(
} }
//文件下载次数加一,为了加快访问速度,异步进行 //文件下载次数加一,为了加快访问速度,异步进行
go tool.SafeMethod(func() { go util.SafeMethod(func() {
this.matterDao.TimesIncrement(uuid) this.matterDao.TimesIncrement(uuid)
}) })

View File

@ -5,7 +5,7 @@ import (
"tank/code/config" "tank/code/config"
"tank/code/logger" "tank/code/logger"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
) )
type IBean interface { type IBean interface {
@ -48,7 +48,7 @@ func (this *Bean) findUser(writer http.ResponseWriter, request *http.Request) *U
//验证用户是否已经登录。 //验证用户是否已经登录。
//登录身份有效期以数据库中记录的为准 //登录身份有效期以数据库中记录的为准
sessionId := tool.GetSessionUuidFromRequest(request, config.COOKIE_AUTH_KEY) sessionId := util.GetSessionUuidFromRequest(request, config.COOKIE_AUTH_KEY)
if sessionId == "" { if sessionId == "" {
return nil return nil
} }

4
code/cache/cache.go vendored
View File

@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"sort" "sort"
"sync" "sync"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -197,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 tool.SafeMethod(table.checkExpire) go util.SafeMethod(table.checkExpire)
}) })
} }
table.Unlock() table.Unlock()

View File

@ -4,7 +4,7 @@ import (
"github.com/json-iterator/go" "github.com/json-iterator/go"
"io/ioutil" "io/ioutil"
"tank/code/logger" "tank/code/logger"
"tank/code/tool" "tank/code/util"
"time" "time"
"unsafe" "unsafe"
) )
@ -133,7 +133,7 @@ func (this *Config) Init() {
func (this *Config) ReadFromConfigFile() { func (this *Config) ReadFromConfigFile() {
//读取配置文件 //读取配置文件
filePath := tool.GetConfPath() + "/tank.json" filePath := util.GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath) content, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
logger.LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath) logger.LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath)
@ -158,18 +158,18 @@ func (this *Config) ReadFromConfigFile() {
//使用配置项中的文件路径 //使用配置项中的文件路径
if this.Item.MatterPath == "" { if this.Item.MatterPath == "" {
this.MatterPath = tool.GetHomePath() + "/matter" this.MatterPath = util.GetHomePath() + "/matter"
} else { } else {
this.MatterPath = this.Item.MatterPath this.MatterPath = this.Item.MatterPath
} }
tool.MakeDirAll(CONFIG.MatterPath) util.MakeDirAll(CONFIG.MatterPath)
//使用配置项中的端口 //使用配置项中的端口
if this.Item.ServerPort != 0 { if this.Item.ServerPort != 0 {
this.ServerPort = this.Item.ServerPort this.ServerPort = this.Item.ServerPort
} }
this.MysqlUrl = tool.GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword) this.MysqlUrl = util.GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword)
this.Installed = true this.Installed = true
logger.LOGGER.Info("使用配置文件:%s", filePath) logger.LOGGER.Info("使用配置文件:%s", filePath)

View File

@ -1,7 +1,7 @@
package code package code
import ( import (
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -53,7 +53,7 @@ func (this *DashboardService) Init() {
func (this *DashboardService) ConfigPost() { func (this *DashboardService) ConfigPost() {
//立即执行数据清洗任务 //立即执行数据清洗任务
go tool.SafeMethod(this.maintain) go util.SafeMethod(this.maintain)
} }
//每日清洗离线数据表。 //每日清洗离线数据表。
@ -61,21 +61,21 @@ func (this *DashboardService) maintain() {
//准备好下次维护日志的时间。 //准备好下次维护日志的时间。
now := time.Now() now := time.Now()
nextTime := tool.FirstMinuteOfDay(tool.Tomorrow()) nextTime := util.FirstMinuteOfDay(util.Tomorrow())
duration := nextTime.Sub(now) duration := nextTime.Sub(now)
this.logger.Info("每日数据汇总,下次时间:%s ", tool.ConvertTimeToDateTimeString(nextTime)) this.logger.Info("每日数据汇总,下次时间:%s ", util.ConvertTimeToDateTimeString(nextTime))
this.maintainTimer = time.AfterFunc(duration, func() { this.maintainTimer = time.AfterFunc(duration, func() {
go tool.SafeMethod(this.maintain) go util.SafeMethod(this.maintain)
}) })
//准备日期开始结尾 //准备日期开始结尾
startTime := tool.FirstSecondOfDay(tool.Yesterday()) startTime := util.FirstSecondOfDay(util.Yesterday())
endTime := tool.LastSecondOfDay(tool.Yesterday()) endTime := util.LastSecondOfDay(util.Yesterday())
dt := tool.ConvertTimeToDateString(startTime) dt := util.ConvertTimeToDateString(startTime)
longTimeAgo := time.Now() longTimeAgo := time.Now()
longTimeAgo = longTimeAgo.AddDate(-20, 0, 0) longTimeAgo = longTimeAgo.AddDate(-20, 0, 0)
this.logger.Info("统计汇总表 %s -> %s", tool.ConvertTimeToDateTimeString(startTime), tool.ConvertTimeToDateTimeString(endTime)) this.logger.Info("统计汇总表 %s -> %s", util.ConvertTimeToDateTimeString(startTime), util.ConvertTimeToDateTimeString(endTime))
//判断昨天的记录是否已经生成,如果生成了就直接删除掉 //判断昨天的记录是否已经生成,如果生成了就直接删除掉
dbDashboard := this.dashboardDao.FindByDt(dt) dbDashboard := this.dashboardDao.FindByDt(dt)

View File

@ -8,7 +8,7 @@ import (
"regexp" "regexp"
"strings" "strings"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
) )
/** /**
@ -87,7 +87,7 @@ func (this *DavController) CheckCurrentUser(writer http.ResponseWriter, request
if user == nil { if user == nil {
panic(result.BadRequest("邮箱或密码错误")) panic(result.BadRequest("邮箱或密码错误"))
} else { } else {
if !tool.MatchBcrypt(password, user.Password) { if !util.MatchBcrypt(password, user.Password) {
panic(result.BadRequest("邮箱或密码错误")) panic(result.BadRequest("邮箱或密码错误"))
} }
} }

View File

@ -10,7 +10,7 @@ import (
"tank/code/dav" "tank/code/dav"
"tank/code/dav/xml" "tank/code/dav/xml"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
) )
/** /**
@ -224,8 +224,8 @@ func (this *DavService) HandlePut(writer http.ResponseWriter, request *http.Requ
fmt.Printf("PUT %s\n", subPath) fmt.Printf("PUT %s\n", subPath)
filename := tool.GetFilenameOfPath(subPath) filename := util.GetFilenameOfPath(subPath)
dirPath := tool.GetDirOfPath(subPath) dirPath := util.GetDirOfPath(subPath)
//寻找符合条件的matter. //寻找符合条件的matter.
dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user) dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user)
@ -256,8 +256,8 @@ func (this *DavService) HandleMkcol(writer http.ResponseWriter, request *http.Re
fmt.Printf("MKCOL %s\n", subPath) fmt.Printf("MKCOL %s\n", subPath)
thisDirName := tool.GetFilenameOfPath(subPath) thisDirName := util.GetFilenameOfPath(subPath)
dirPath := tool.GetDirOfPath(subPath) dirPath := util.GetDirOfPath(subPath)
//寻找符合条件的matter. //寻找符合条件的matter.
dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user) dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user)
@ -341,9 +341,9 @@ func (this *DavService) prepareMoveCopy(
panic(result.BadRequest("目标前缀必须为:%s", WEBDAV_PREFFIX)) panic(result.BadRequest("目标前缀必须为:%s", WEBDAV_PREFFIX))
} }
destinationName = tool.GetFilenameOfPath(destinationPath) destinationName = util.GetFilenameOfPath(destinationPath)
destinationDirPath = tool.GetDirOfPath(destinationPath) destinationDirPath = util.GetDirOfPath(destinationPath)
srcDirPath = tool.GetDirOfPath(subPath) srcDirPath = util.GetDirOfPath(subPath)
overwrite = false overwrite = false
if overwriteStr == "T" { if overwriteStr == "T" {

View File

@ -12,7 +12,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -266,7 +266,7 @@ func DownloadFile(
var ctype string var ctype string
if !haveType { if !haveType {
//使用mimeUtil来获取mime //使用mimeUtil来获取mime
ctype = tool.GetFallbackMimeType(filename, "") ctype = util.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

@ -4,7 +4,7 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"tank/code/config" "tank/code/config"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -65,7 +65,7 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
//将文件信息存入数据库中。 //将文件信息存入数据库中。
footprint := &Footprint{ footprint := &Footprint{
Ip: tool.GetIpAddress(request), Ip: util.GetIpAddress(request),
Host: request.Host, Host: request.Host,
Uri: request.URL.Path, Uri: request.URL.Path,
Params: paramsString, Params: paramsString,

View File

@ -6,7 +6,7 @@ import (
"github.com/nu7hatch/gouuid" "github.com/nu7hatch/gouuid"
"os" "os"
"path/filepath" "path/filepath"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -152,7 +152,7 @@ func (this *ImageCacheDao) deleteFileAndDir(imageCache *ImageCache) {
} }
//如果这一层文件夹是空的,那么删除文件夹本身。 //如果这一层文件夹是空的,那么删除文件夹本身。
tool.DeleteEmptyDirRecursive(dirPath) util.DeleteEmptyDirRecursive(dirPath)
} }

View File

@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"tank/code/tool" "tank/code/util"
) )
//@Service //@Service
@ -180,7 +180,7 @@ func (this *ImageCacheService) ResizeImage(request *http.Request, filePath strin
func (this *ImageCacheService) cacheImage(writer http.ResponseWriter, request *http.Request, matter *Matter) *ImageCache { func (this *ImageCacheService) cacheImage(writer http.ResponseWriter, request *http.Request, matter *Matter) *ImageCache {
//当前的文件是否是图片,只有图片才能处理。 //当前的文件是否是图片,只有图片才能处理。
extension := tool.GetExtension(matter.Name) extension := util.GetExtension(matter.Name)
formats := map[string]imaging.Format{ formats := map[string]imaging.Format{
".jpg": imaging.JPEG, ".jpg": imaging.JPEG,
".jpeg": imaging.JPEG, ".jpeg": imaging.JPEG,
@ -204,13 +204,13 @@ func (this *ImageCacheService) cacheImage(writer http.ResponseWriter, request *h
//resize图片 //resize图片
dstImage := this.ResizeImage(request, matter.AbsolutePath()) dstImage := this.ResizeImage(request, matter.AbsolutePath())
cacheImageName := tool.GetSimpleFileName(matter.Name) + "_" + mode + extension cacheImageName := util.GetSimpleFileName(matter.Name) + "_" + mode + extension
cacheImageRelativePath := tool.GetSimpleFileName(matter.Path) + "_" + mode + extension cacheImageRelativePath := util.GetSimpleFileName(matter.Path) + "_" + mode + extension
cacheImageAbsolutePath := GetUserCacheRootDir(user.Username) + tool.GetSimpleFileName(matter.Path) + "_" + mode + extension cacheImageAbsolutePath := GetUserCacheRootDir(user.Username) + util.GetSimpleFileName(matter.Path) + "_" + mode + extension
//创建目录。 //创建目录。
dir := filepath.Dir(cacheImageAbsolutePath) dir := filepath.Dir(cacheImageAbsolutePath)
tool.MakeDirAll(dir) util.MakeDirAll(dir)
fileWriter, err := os.Create(cacheImageAbsolutePath) fileWriter, err := os.Create(cacheImageAbsolutePath)
this.PanicError(err) this.PanicError(err)

View File

@ -13,7 +13,7 @@ import (
"strconv" "strconv"
"tank/code/config" "tank/code/config"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -97,7 +97,7 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
mysqlPort = tmp mysqlPort = tmp
} }
mysqlUrl := tool.GetMysqlUrl(mysqlPort, mysqlHost, mysqlSchema, mysqlUsername, mysqlPassword) mysqlUrl := util.GetMysqlUrl(mysqlPort, mysqlHost, mysqlSchema, mysqlUsername, mysqlPassword)
this.logger.Info("连接MySQL %s", mysqlUrl) this.logger.Info("连接MySQL %s", mysqlUrl)
@ -126,9 +126,9 @@ func (this *InstallController) closeDbConnection(db *gorm.DB) {
func (this *InstallController) getCreateSQLFromFile(tableName string) string { func (this *InstallController) getCreateSQLFromFile(tableName string) string {
//1. 从当前安装目录db下去寻找建表文件。 //1. 从当前安装目录db下去寻找建表文件。
homePath := tool.GetHomePath() homePath := util.GetHomePath()
filePath := homePath + "/db/" + tableName + ".sql" filePath := homePath + "/db/" + tableName + ".sql"
exists, err := tool.PathExists(filePath) exists, err := util.PathExists(filePath)
if err != nil { if err != nil {
panic(result.Server("从安装目录判断建表语句文件是否存在时出错!")) panic(result.Server("从安装目录判断建表语句文件是否存在时出错!"))
} }
@ -140,7 +140,7 @@ func (this *InstallController) getCreateSQLFromFile(tableName string) string {
filePath1 := filePath filePath1 := filePath
filePath = build.Default.GOPATH + "/src/tank/build/db/" + tableName + ".sql" filePath = build.Default.GOPATH + "/src/tank/build/db/" + tableName + ".sql"
exists, err = tool.PathExists(filePath) exists, err = util.PathExists(filePath)
if err != nil { if err != nil {
panic(result.Server("从GOPATH判断建表语句文件是否存在时出错")) panic(result.Server("从GOPATH判断建表语句文件是否存在时出错"))
} }
@ -344,7 +344,7 @@ func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *
user.Sort = time.Now().UnixNano() / 1e6 user.Sort = time.Now().UnixNano() / 1e6
user.Role = USER_ROLE_ADMINISTRATOR user.Role = USER_ROLE_ADMINISTRATOR
user.Username = adminUsername user.Username = adminUsername
user.Password = tool.GetBcrypt(adminPassword) user.Password = util.GetBcrypt(adminPassword)
user.Email = adminEmail user.Email = adminEmail
user.Phone = "" user.Phone = ""
user.Gender = USER_GENDER_UNKNOWN user.Gender = USER_GENDER_UNKNOWN
@ -381,7 +381,7 @@ func (this *InstallController) ValidateAdmin(writer http.ResponseWriter, request
panic(result.BadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail))) panic(result.BadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail)))
} }
if !tool.MatchBcrypt(adminPassword, existEmailUser.Password) { if !util.MatchBcrypt(adminPassword, existEmailUser.Password) {
panic(result.BadRequest("邮箱或密码错误")) panic(result.BadRequest("邮箱或密码错误"))
} }
@ -447,7 +447,7 @@ func (this *InstallController) Finish(writer http.ResponseWriter, request *http.
jsonStr, _ := jsoniter.ConfigCompatibleWithStandardLibrary.MarshalIndent(configItem, "", " ") jsonStr, _ := jsoniter.ConfigCompatibleWithStandardLibrary.MarshalIndent(configItem, "", " ")
//写入到配置文件中不能使用os.O_APPEND 否则会追加) //写入到配置文件中不能使用os.O_APPEND 否则会追加)
filePath := tool.GetConfPath() + "/tank.json" filePath := util.GetConfPath() + "/tank.json"
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0777) f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0777)
this.PanicError(err) this.PanicError(err)
_, err = f.Write(jsonStr) _, err = f.Write(jsonStr)

View File

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

View File

@ -6,7 +6,7 @@ import (
"os" "os"
"tank/code/config" "tank/code/config"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -285,7 +285,7 @@ func (this *MatterDao) Delete(matter *Matter) {
this.PanicError(db.Error) this.PanicError(db.Error)
//从磁盘中删除该文件夹。 //从磁盘中删除该文件夹。
tool.DeleteEmptyDir(matter.AbsolutePath()) util.DeleteEmptyDir(matter.AbsolutePath())
} else { } else {

View File

@ -3,7 +3,7 @@ package code
import ( import (
"fmt" "fmt"
"tank/code/config" "tank/code/config"
"tank/code/tool" "tank/code/util"
) )
const ( const (
@ -48,7 +48,7 @@ func (this *Matter) AbsolutePath() string {
// 获取该Matter的MimeType // 获取该Matter的MimeType
func (this *Matter) MimeType() string { func (this *Matter) MimeType() string {
return tool.GetMimeType(tool.GetExtension(this.Name)) return util.GetMimeType(util.GetExtension(this.Name))
} }

View File

@ -8,7 +8,7 @@ import (
"strings" "strings"
"tank/code/download" "tank/code/download"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
) )
/** /**
@ -113,10 +113,10 @@ func (this *MatterService) Upload(file io.Reader, user *User, dirMatter *Matter,
fileRelativePath := dirRelativePath + "/" + filename fileRelativePath := dirRelativePath + "/" + filename
//创建父文件夹 //创建父文件夹
tool.MakeDirAll(dirAbsolutePath) util.MakeDirAll(dirAbsolutePath)
//如果文件已经存在了,那么直接覆盖。 //如果文件已经存在了,那么直接覆盖。
exist, err := tool.PathExists(fileAbsolutePath) exist, err := util.PathExists(fileAbsolutePath)
this.PanicError(err) this.PanicError(err)
if exist { if exist {
this.logger.Error("%s已经存在将其删除", fileAbsolutePath) this.logger.Error("%s已经存在将其删除", fileAbsolutePath)
@ -135,7 +135,7 @@ func (this *MatterService) Upload(file io.Reader, user *User, dirMatter *Matter,
fileSize, err := io.Copy(destFile, file) fileSize, err := io.Copy(destFile, file)
this.PanicError(err) this.PanicError(err)
this.logger.Info("上传文件 %s 大小为 %v ", filename, tool.HumanFileSize(fileSize)) this.logger.Info("上传文件 %s 大小为 %v ", filename, util.HumanFileSize(fileSize))
//判断用户自身上传大小的限制。 //判断用户自身上传大小的限制。
if user.SizeLimit >= 0 { if user.SizeLimit >= 0 {
@ -144,7 +144,7 @@ func (this *MatterService) Upload(file io.Reader, user *User, dirMatter *Matter,
err = os.Remove(fileAbsolutePath) err = os.Remove(fileAbsolutePath)
this.PanicError(err) this.PanicError(err)
panic(result.BadRequest("文件大小超出限制 %s > %s ", tool.HumanFileSize(user.SizeLimit), tool.HumanFileSize(fileSize))) panic(result.BadRequest("文件大小超出限制 %s > %s ", util.HumanFileSize(user.SizeLimit), util.HumanFileSize(fileSize)))
} }
} }
@ -235,7 +235,7 @@ func (this *MatterService) createDirectory(dirMatter *Matter, name string, user
relativePath := dirMatter.Path + "/" + name relativePath := dirMatter.Path + "/" + name
//磁盘中创建文件夹。 //磁盘中创建文件夹。
dirPath := tool.MakeDirAll(absolutePath) dirPath := util.MakeDirAll(absolutePath)
this.logger.Info("Create Directory: %s", dirPath) this.logger.Info("Create Directory: %s", dirPath)
//数据库中创建文件夹。 //数据库中创建文件夹。
@ -446,7 +446,7 @@ func (this *MatterService) copy(srcMatter *Matter, destDirMatter *Matter, name s
srcAbsolutePath := srcMatter.AbsolutePath() srcAbsolutePath := srcMatter.AbsolutePath()
//物理文件进行复制 //物理文件进行复制
tool.CopyFile(srcAbsolutePath, destAbsolutePath) util.CopyFile(srcAbsolutePath, destAbsolutePath)
//创建新文件的数据库信息。 //创建新文件的数据库信息。
newMatter := &Matter{ newMatter := &Matter{
@ -524,8 +524,8 @@ func (this *MatterService) AtomicRename(matter *Matter, name string, user *User)
//如果源是文件夹 //如果源是文件夹
oldAbsolutePath := matter.AbsolutePath() oldAbsolutePath := matter.AbsolutePath()
absoluteDirPath := tool.GetDirOfPath(oldAbsolutePath) absoluteDirPath := util.GetDirOfPath(oldAbsolutePath)
relativeDirPath := tool.GetDirOfPath(matter.Path) relativeDirPath := util.GetDirOfPath(matter.Path)
newAbsolutePath := absoluteDirPath + "/" + name newAbsolutePath := absoluteDirPath + "/" + name
//物理文件一口气移动 //物理文件一口气移动
@ -547,8 +547,8 @@ func (this *MatterService) AtomicRename(matter *Matter, name string, user *User)
//如果源是普通文件 //如果源是普通文件
oldAbsolutePath := matter.AbsolutePath() oldAbsolutePath := matter.AbsolutePath()
absoluteDirPath := tool.GetDirOfPath(oldAbsolutePath) absoluteDirPath := util.GetDirOfPath(oldAbsolutePath)
relativeDirPath := tool.GetDirOfPath(matter.Path) relativeDirPath := util.GetDirOfPath(matter.Path)
newAbsolutePath := absoluteDirPath + "/" + name newAbsolutePath := absoluteDirPath + "/" + name
//物理文件进行移动 //物理文件进行移动

View File

@ -3,7 +3,7 @@ package code
import ( import (
"net/http" "net/http"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
) )
type PreferenceController struct { type PreferenceController struct {
@ -91,7 +91,7 @@ func (this *PreferenceController) SystemCleanup(writer http.ResponseWriter, requ
user := this.checkUser(writer, request) user := this.checkUser(writer, request)
password := request.FormValue("password") password := request.FormValue("password")
if !tool.MatchBcrypt(password, user.Password) { if !util.MatchBcrypt(password, user.Password) {
panic(result.BadRequest("密码错误,不能执行!")) panic(result.BadRequest("密码错误,不能执行!"))
} }

View File

@ -10,7 +10,7 @@ import (
"tank/code/config" "tank/code/config"
"tank/code/logger" "tank/code/logger"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -108,7 +108,7 @@ func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http
} }
//错误情况记录。 //错误情况记录。
go tool.SafeMethod(func() { go util.SafeMethod(func() {
this.footprintService.Trace(writer, request, time.Now().Sub(startTime), false) this.footprintService.Trace(writer, request, time.Now().Sub(startTime), false)
}) })
} }
@ -157,7 +157,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} }
//正常的访问记录会落到这里。 //正常的访问记录会落到这里。
go tool.SafeMethod(func() { go util.SafeMethod(func() {
this.footprintService.Trace(writer, request, time.Now().Sub(startTime), true) this.footprintService.Trace(writer, request, time.Now().Sub(startTime), true)
}) })
@ -172,7 +172,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} else { } else {
//当作静态资源处理。默认从当前文件下面的static文件夹中取东西。 //当作静态资源处理。默认从当前文件下面的static文件夹中取东西。
dir := tool.GetHtmlPath() dir := util.GetHtmlPath()
requestURI := request.RequestURI requestURI := request.RequestURI
if requestURI == "" || request.RequestURI == "/" { if requestURI == "" || request.RequestURI == "/" {
@ -180,16 +180,16 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} }
filePath := dir + requestURI filePath := dir + requestURI
exists, _ := tool.PathExists(filePath) exists, _ := util.PathExists(filePath)
if !exists { if !exists {
filePath = dir + "/index.html" filePath = dir + "/index.html"
exists, _ = tool.PathExists(filePath) exists, _ = util.PathExists(filePath)
if !exists { if !exists {
panic(fmt.Sprintf("404 not found:%s", filePath)) panic(fmt.Sprintf("404 not found:%s", filePath))
} }
} }
writer.Header().Set("Content-Type", tool.GetMimeType(tool.GetExtension(filePath))) writer.Header().Set("Content-Type", util.GetMimeType(util.GetExtension(filePath)))
diskFile, err := os.Open(filePath) diskFile, err := os.Open(filePath)
if err != nil { if err != nil {

View File

@ -6,7 +6,7 @@ import (
"strconv" "strconv"
"tank/code/config" "tank/code/config"
"tank/code/result" "tank/code/result"
"tank/code/tool" "tank/code/util"
"time" "time"
) )
@ -60,7 +60,7 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
panic(result.BadRequest("邮箱或密码错误")) panic(result.BadRequest("邮箱或密码错误"))
} else { } else {
if !tool.MatchBcrypt(password, user.Password) { if !util.MatchBcrypt(password, user.Password) {
panic(result.BadRequest("邮箱或密码错误")) panic(result.BadRequest("邮箱或密码错误"))
} }
@ -73,7 +73,7 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
//持久化用户的session. //持久化用户的session.
session := &Session{ session := &Session{
UserUuid: user.Uuid, UserUuid: user.Uuid,
Ip: tool.GetIpAddress(request), Ip: util.GetIpAddress(request),
ExpireTime: expiration, ExpireTime: expiration,
} }
session.UpdateTime = time.Now() session.UpdateTime = time.Now()
@ -90,7 +90,7 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
//更新用户上次登录时间和ip //更新用户上次登录时间和ip
user.LastTime = time.Now() user.LastTime = time.Now()
user.LastIp = tool.GetIpAddress(request) user.LastIp = util.GetIpAddress(request)
this.userDao.Save(user) this.userDao.Save(user)
return this.Success(user) return this.Success(user)
@ -144,7 +144,7 @@ func (this *UserController) Create(writer http.ResponseWriter, request *http.Req
user := &User{ user := &User{
Role: GetRole(role), Role: GetRole(role),
Username: username, Username: username,
Password: tool.GetBcrypt(password), Password: util.GetBcrypt(password),
Email: email, Email: email,
Phone: phone, Phone: phone,
Gender: gender, Gender: gender,
@ -364,11 +364,11 @@ func (this *UserController) ChangePassword(writer http.ResponseWriter, request *
return this.Success(user) return this.Success(user)
} }
if !tool.MatchBcrypt(oldPassword, user.Password) { if !util.MatchBcrypt(oldPassword, user.Password) {
panic(result.BadRequest("旧密码不正确!")) panic(result.BadRequest("旧密码不正确!"))
} }
user.Password = tool.GetBcrypt(newPassword) user.Password = util.GetBcrypt(newPassword)
user = this.userDao.Save(user) user = this.userDao.Save(user)
@ -395,7 +395,7 @@ func (this *UserController) ResetPassword(writer http.ResponseWriter, request *h
user := this.userDao.CheckByUuid(userUuid) user := this.userDao.CheckByUuid(userUuid)
user.Password = tool.GetBcrypt(password) user.Password = util.GetBcrypt(password)
user = this.userDao.Save(user) user = this.userDao.Save(user)

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"crypto/md5" "crypto/md5"

View File

@ -1,4 +1,4 @@
package tool package util
//带有panic恢复的方法 //带有panic恢复的方法

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"os" "os"

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"net/http" "net/http"

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package tool package util
import ( import (
"regexp" "regexp"