Refine the directories.

This commit is contained in:
zicla
2019-04-26 02:30:04 +08:00
parent 61b14fe82b
commit b3c52ea50e
40 changed files with 214 additions and 162 deletions

12
main.go
View File

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

View File

@ -6,6 +6,7 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
"time" "time"
) )
@ -129,7 +130,7 @@ func (this *AlienController) CheckRequestUser(writer http.ResponseWriter, reques
if user == nil { if user == nil {
panic(`邮箱或密码错误`) panic(`邮箱或密码错误`)
} else { } else {
if !MatchBcrypt(password, user.Password) { if !tool.MatchBcrypt(password, user.Password) {
panic(`邮箱或密码错误`) panic(`邮箱或密码错误`)
} }
} }
@ -209,7 +210,7 @@ func (this *AlienController) FetchUploadToken(writer http.ResponseWriter, reques
Filename: filename, Filename: filename,
Privacy: privacy, Privacy: privacy,
Size: size, Size: size,
Ip: GetIpAddress(request), Ip: tool.GetIpAddress(request),
} }
uploadToken = this.uploadTokenDao.Create(uploadToken) uploadToken = this.uploadTokenDao.Create(uploadToken)
@ -402,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: GetIpAddress(request), Ip: tool.GetIpAddress(request),
} }
downloadToken = this.downloadTokenDao.Create(downloadToken) downloadToken = this.downloadTokenDao.Create(downloadToken)

View File

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

View File

@ -3,6 +3,7 @@ package rest
import ( import (
"math" "math"
"reflect" "reflect"
"tank/rest/config"
"time" "time"
) )
@ -39,7 +40,7 @@ func (this *Base) Map() map[string]interface{} {
} }
func (this *Base) TableName() string { func (this *Base) TableName() string {
return TABLE_PREFIX + "base" return config.TABLE_PREFIX + "base"
} }
//分页类 //分页类

View File

@ -3,7 +3,9 @@ package rest
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"tank/rest/config"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
) )
type IBean interface { type IBean interface {
@ -18,11 +20,11 @@ type IBean interface {
} }
type Bean struct { type Bean struct {
logger *Logger logger *tool.Logger
} }
func (this *Bean) Init() { func (this *Bean) Init() {
this.logger = LOGGER this.logger = tool.LOGGER
} }
func (this *Bean) ConfigPost() { func (this *Bean) ConfigPost() {
@ -66,7 +68,7 @@ func (this *Bean) findUser(writer http.ResponseWriter, request *http.Request) *U
//验证用户是否已经登录。 //验证用户是否已经登录。
//登录身份有效期以数据库中记录的为准 //登录身份有效期以数据库中记录的为准
sessionId := GetSessionUuidFromRequest(request) sessionId := tool.GetSessionUuidFromRequest(request, config.COOKIE_AUTH_KEY)
if sessionId == "" { if sessionId == "" {
return nil return nil
} }

View File

@ -1,8 +1,9 @@
package rest package config
import ( import (
"github.com/json-iterator/go" "github.com/json-iterator/go"
"io/ioutil" "io/ioutil"
"tank/rest/tool"
"time" "time"
"unsafe" "unsafe"
) )
@ -64,7 +65,7 @@ type ConfigItem struct {
func (this *ConfigItem) validate() bool { func (this *ConfigItem) validate() bool {
if this.ServerPort == 0 { if this.ServerPort == 0 {
LOGGER.Error("ServerPort 未配置") tool.LOGGER.Error("ServerPort 未配置")
return false return false
} else { } else {
//只要配置文件中有配置端口,就使用。 //只要配置文件中有配置端口,就使用。
@ -72,27 +73,27 @@ func (this *ConfigItem) validate() bool {
} }
if this.MysqlUsername == "" { if this.MysqlUsername == "" {
LOGGER.Error("MysqlUsername 未配置") tool.LOGGER.Error("MysqlUsername 未配置")
return false return false
} }
if this.MysqlPassword == "" { if this.MysqlPassword == "" {
LOGGER.Error("MysqlPassword 未配置") tool.LOGGER.Error("MysqlPassword 未配置")
return false return false
} }
if this.MysqlHost == "" { if this.MysqlHost == "" {
LOGGER.Error("MysqlHost 未配置") tool.LOGGER.Error("MysqlHost 未配置")
return false return false
} }
if this.MysqlPort == 0 { if this.MysqlPort == 0 {
LOGGER.Error("MysqlPort 未配置") tool.LOGGER.Error("MysqlPort 未配置")
return false return false
} }
if this.MysqlSchema == "" { if this.MysqlSchema == "" {
LOGGER.Error("MysqlSchema 未配置") tool.LOGGER.Error("MysqlSchema 未配置")
return false return false
} }
@ -131,17 +132,17 @@ func (this *Config) Init() {
func (this *Config) ReadFromConfigFile() { func (this *Config) ReadFromConfigFile() {
//读取配置文件 //读取配置文件
filePath := GetConfPath() + "/tank.json" filePath := tool.GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath) content, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath) tool.LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath)
this.Installed = false this.Installed = false
} else { } else {
this.Item = &ConfigItem{} this.Item = &ConfigItem{}
LOGGER.Warn("读取配置文件:%s", filePath) tool.LOGGER.Warn("读取配置文件:%s", filePath)
err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item) err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item)
if err != nil { if err != nil {
LOGGER.Error("配置文件格式错误! 即将进入安装过程!") tool.LOGGER.Error("配置文件格式错误! 即将进入安装过程!")
this.Installed = false this.Installed = false
return return
} }
@ -149,29 +150,29 @@ func (this *Config) ReadFromConfigFile() {
//验证项是否齐全 //验证项是否齐全
itemValidate := this.Item.validate() itemValidate := this.Item.validate()
if !itemValidate { if !itemValidate {
LOGGER.Error("配置文件信息不齐全! 即将进入安装过程!") tool.LOGGER.Error("配置文件信息不齐全! 即将进入安装过程!")
this.Installed = false this.Installed = false
return return
} }
//使用配置项中的文件路径 //使用配置项中的文件路径
if this.Item.MatterPath == "" { if this.Item.MatterPath == "" {
this.MatterPath = GetHomePath() + "/matter" this.MatterPath = tool.GetHomePath() + "/matter"
} else { } else {
this.MatterPath = this.Item.MatterPath this.MatterPath = this.Item.MatterPath
} }
MakeDirAll(CONFIG.MatterPath) tool.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 = 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
LOGGER.Info("使用配置文件:%s", filePath) tool.LOGGER.Info("使用配置文件:%s", filePath)
LOGGER.Info("上传文件存放路径:%s", this.MatterPath) tool.LOGGER.Info("上传文件存放路径:%s", this.MatterPath)
} }
} }

View File

@ -4,6 +4,8 @@ import (
"fmt" "fmt"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"reflect" "reflect"
"tank/rest/config"
"tank/rest/tool"
) )
//全局唯一的上下文(在main函数中初始化) //全局唯一的上下文(在main函数中初始化)
@ -14,7 +16,7 @@ type Context struct {
//数据库连接 //数据库连接
DB *gorm.DB DB *gorm.DB
//session缓存 //session缓存
SessionCache *CacheTable SessionCache *tool.CacheTable
//各类的Bean Map。这里面是包含ControllerMap中所有元素 //各类的Bean Map。这里面是包含ControllerMap中所有元素
BeanMap map[string]IBean BeanMap map[string]IBean
//只包含了Controller的map //只包含了Controller的map
@ -27,7 +29,7 @@ type Context struct {
func (this *Context) Init() { func (this *Context) Init() {
//创建一个用于存储session的缓存。 //创建一个用于存储session的缓存。
this.SessionCache = NewCacheTable() this.SessionCache = tool.NewCacheTable()
//初始化Map //初始化Map
this.BeanMap = make(map[string]IBean) this.BeanMap = make(map[string]IBean)
@ -50,10 +52,10 @@ func (this *Context) Init() {
func (this *Context) OpenDb() { func (this *Context) OpenDb() {
var err error = nil var err error = nil
this.DB, err = gorm.Open("mysql", CONFIG.MysqlUrl) this.DB, err = gorm.Open("mysql", config.CONFIG.MysqlUrl)
if err != nil { if err != nil {
LOGGER.Panic("failed to connect mysql database") tool.LOGGER.Panic("failed to connect mysql database")
} }
//是否打开sql日志(在调试阶段可以打开以方便查看执行的SQL) //是否打开sql日志(在调试阶段可以打开以方便查看执行的SQL)
@ -80,7 +82,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 {
LOGGER.Error(fmt.Sprintf(err)) tool.LOGGER.Error(fmt.Sprintf(err))
} else { } else {
this.BeanMap[typeName] = element this.BeanMap[typeName] = element
@ -92,7 +94,7 @@ func (this *Context) registerBean(bean IBean) {
} }
} else { } else {
LOGGER.Panic("注册的【%s】不是Bean类型。", typeName) tool.LOGGER.Panic("注册的【%s】不是Bean类型。", typeName)
} }
} }
@ -162,7 +164,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 {
LOGGER.Panic("【%s】没有注册。", typeName) tool.LOGGER.Panic("【%s】没有注册。", typeName)
return nil return nil
} }
} }
@ -179,7 +181,7 @@ func (this *Context) initBeans() {
//系统如果安装好了就调用这个方法。 //系统如果安装好了就调用这个方法。
func (this *Context) InstallOk() { func (this *Context) InstallOk() {
if CONFIG.Installed { if config.CONFIG.Installed {
this.OpenDb() this.OpenDb()
for _, bean := range this.BeanMap { for _, bean := range this.BeanMap {

View File

@ -1,5 +1,7 @@
package rest package rest
import "tank/rest/config"
/** /**
* 系统的所有访问记录均记录在此 * 系统的所有访问记录均记录在此
*/ */
@ -19,7 +21,7 @@ type Dashboard struct {
// set File's table name to be `profiles` // set File's table name to be `profiles`
func (this *Dashboard) TableName() string { func (this *Dashboard) TableName() string {
return TABLE_PREFIX + "dashboard" return config.TABLE_PREFIX + "dashboard"
} }
/** /**

View File

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

View File

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

View File

@ -1,17 +1,17 @@
package rest package rest
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"path"
"regexp" "regexp"
"strings" "strings"
"tank/rest/dav" "tank/rest/dav"
"tank/rest/dav/xml" "tank/rest/dav/xml"
"tank/rest/tool"
) )
/** /**
* *
* WebDav协议文档 * WebDav协议文档
@ -223,8 +223,8 @@ func (this *DavService) HandlePut(writer http.ResponseWriter, request *http.Requ
fmt.Printf("PUT %s\n", subPath) fmt.Printf("PUT %s\n", subPath)
filename := GetFilenameOfPath(subPath) filename := tool.GetFilenameOfPath(subPath)
dirPath := GetDirOfPath(subPath) dirPath := tool.GetDirOfPath(subPath)
//寻找符合条件的matter. //寻找符合条件的matter.
dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user) dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user)
@ -255,8 +255,8 @@ func (this *DavService) HandleMkcol(writer http.ResponseWriter, request *http.Re
fmt.Printf("MKCOL %s\n", subPath) fmt.Printf("MKCOL %s\n", subPath)
thisDirName := GetFilenameOfPath(subPath) thisDirName := tool.GetFilenameOfPath(subPath)
dirPath := GetDirOfPath(subPath) dirPath := tool.GetDirOfPath(subPath)
//寻找符合条件的matter. //寻找符合条件的matter.
dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user) dirMatter := this.matterDao.CheckWithRootByPath(dirPath, user)
@ -327,6 +327,9 @@ func (this *DavService) prepareMoveCopy(
fullDestinationPath = destinationUrl.Path fullDestinationPath = destinationUrl.Path
} }
//去除 路径中的相对路径 比如 /a/b/../ => /a/
fullDestinationPath = path.Clean(fullDestinationPath)
//去除前缀 //去除前缀
pattern := fmt.Sprintf(`^%s(.*)$`, WEBDAV_PREFFIX) pattern := fmt.Sprintf(`^%s(.*)$`, WEBDAV_PREFFIX)
reg := regexp.MustCompile(pattern) reg := regexp.MustCompile(pattern)
@ -337,9 +340,9 @@ func (this *DavService) prepareMoveCopy(
this.PanicBadRequest("目标前缀必须为:%s", WEBDAV_PREFFIX) this.PanicBadRequest("目标前缀必须为:%s", WEBDAV_PREFFIX)
} }
destinationName = GetFilenameOfPath(destinationPath) destinationName = tool.GetFilenameOfPath(destinationPath)
destinationDirPath = GetDirOfPath(destinationPath) destinationDirPath = tool.GetDirOfPath(destinationPath)
srcDirPath = GetDirOfPath(subPath) srcDirPath = tool.GetDirOfPath(subPath)
overwrite = false overwrite = false
if overwriteStr == "T" { if overwriteStr == "T" {
@ -360,6 +363,9 @@ func (this *DavService) prepareMoveCopy(
this.PanicBadRequest("你不能移动根目录!") this.PanicBadRequest("你不能移动根目录!")
} }
//寻找目标文件夹matter
destDirMatter = this.matterDao.CheckWithRootByPath(destinationDirPath, user)
return srcMatter, destDirMatter, srcDirPath, destinationDirPath, destinationName, overwrite return srcMatter, destDirMatter, srcDirPath, destinationDirPath, destinationName, overwrite
} }
@ -389,7 +395,7 @@ func (this *DavService) HandleCopy(writer http.ResponseWriter, request *http.Req
srcMatter, destDirMatter, _, _, destinationName, overwrite := this.prepareMoveCopy(writer, request, user, subPath) srcMatter, destDirMatter, _, _, destinationName, overwrite := this.prepareMoveCopy(writer, request, user, subPath)
//复制到新目录中去。 //复制到新目录中去。
this.matterService.AtomicCopy(srcMatter, destDirMatter, destinationName,overwrite) this.matterService.AtomicCopy(srcMatter, destDirMatter, destinationName, overwrite)
this.logger.Info("完成复制 %s => %s", subPath, destDirMatter.Path) this.logger.Info("完成复制 %s => %s", subPath, destDirMatter.Path)

View File

@ -1,6 +1,7 @@
package rest package rest
import ( import (
"tank/rest/config"
"time" "time"
) )
@ -13,5 +14,5 @@ type DownloadToken struct {
} }
func (this *DownloadToken) TableName() string { func (this *DownloadToken) TableName() string {
return TABLE_PREFIX + "download_token" return config.TABLE_PREFIX + "download_token"
} }

View File

@ -1,5 +1,7 @@
package rest package rest
import "tank/rest/config"
/** /**
* 系统的所有访问记录均记录在此 * 系统的所有访问记录均记录在此
*/ */
@ -16,5 +18,5 @@ type Footprint struct {
// set File's table name to be `profiles` // set File's table name to be `profiles`
func (this *Footprint) TableName() string { func (this *Footprint) TableName() string {
return TABLE_PREFIX + "footprint" return config.TABLE_PREFIX + "footprint"
} }

View File

@ -3,6 +3,8 @@ package rest
import ( import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"tank/rest/config"
"tank/rest/tool"
"time" "time"
) )
@ -63,7 +65,7 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
//将文件信息存入数据库中。 //将文件信息存入数据库中。
footprint := &Footprint{ footprint := &Footprint{
Ip: GetIpAddress(request), Ip: tool.GetIpAddress(request),
Host: request.Host, Host: request.Host,
Uri: request.URL.Path, Uri: request.URL.Path,
Params: paramsString, Params: paramsString,
@ -72,7 +74,7 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
} }
//有可能DB尚且没有配置 直接打印出内容,并且退出 //有可能DB尚且没有配置 直接打印出内容,并且退出
if CONFIG.Installed { if config.CONFIG.Installed {
user := this.findUser(writer, request) user := this.findUser(writer, request)
userUuid := "" userUuid := ""
if user != nil { if user != nil {

View File

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

View File

@ -1,5 +1,9 @@
package rest package rest
import (
"tank/rest/config"
)
/** /**
* 图片缓存,对于那些处理过的图片,统一管理在这里。 * 图片缓存,对于那些处理过的图片,统一管理在这里。
*/ */
@ -19,7 +23,7 @@ type ImageCache struct {
// set File's table name to be `profiles` // set File's table name to be `profiles`
func (this *ImageCache) TableName() string { func (this *ImageCache) TableName() string {
return TABLE_PREFIX + "image_cache" return config.TABLE_PREFIX + "image_cache"
} }
// 获取该ImageCache的绝对路径。path代表的是相对路径。 // 获取该ImageCache的绝对路径。path代表的是相对路径。

View File

@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"tank/rest/util" "tank/rest/tool"
) )
//@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 := util.GetExtension(matter.Name) extension := tool.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 := util.GetSimpleFileName(matter.Name) + "_" + mode + extension cacheImageName := tool.GetSimpleFileName(matter.Name) + "_" + mode + extension
cacheImageRelativePath := util.GetSimpleFileName(matter.Path) + "_" + mode + extension cacheImageRelativePath := tool.GetSimpleFileName(matter.Path) + "_" + mode + extension
cacheImageAbsolutePath := GetUserCacheRootDir(user.Username) + util.GetSimpleFileName(matter.Path) + "_" + mode + extension cacheImageAbsolutePath := GetUserCacheRootDir(user.Username) + tool.GetSimpleFileName(matter.Path) + "_" + mode + extension
//创建目录。 //创建目录。
dir := filepath.Dir(cacheImageAbsolutePath) dir := filepath.Dir(cacheImageAbsolutePath)
MakeDirAll(dir) tool.MakeDirAll(dir)
fileWriter, err := os.Create(cacheImageAbsolutePath) fileWriter, err := os.Create(cacheImageAbsolutePath)
this.PanicError(err) this.PanicError(err)

View File

@ -11,7 +11,9 @@ import (
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
"tank/rest/config"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
"time" "time"
) )
@ -95,7 +97,7 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
mysqlPort = tmp mysqlPort = tmp
} }
mysqlUrl := GetMysqlUrl(mysqlPort, mysqlHost, mysqlSchema, mysqlUsername, mysqlPassword) mysqlUrl := tool.GetMysqlUrl(mysqlPort, mysqlHost, mysqlSchema, mysqlUsername, mysqlPassword)
this.logger.Info("连接MySQL %s", mysqlUrl) this.logger.Info("连接MySQL %s", mysqlUrl)
@ -124,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 := GetHomePath() homePath := tool.GetHomePath()
filePath := homePath + "/db/" + tableName + ".sql" filePath := homePath + "/db/" + tableName + ".sql"
exists, err := PathExists(filePath) exists, err := tool.PathExists(filePath)
if err != nil { if err != nil {
this.PanicServer("从安装目录判断建表语句文件是否存在时出错!") this.PanicServer("从安装目录判断建表语句文件是否存在时出错!")
} }
@ -138,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 = PathExists(filePath) exists, err = tool.PathExists(filePath)
if err != nil { if err != nil {
this.PanicServer("从GOPATH判断建表语句文件是否存在时出错") this.PanicServer("从GOPATH判断建表语句文件是否存在时出错")
} }
@ -342,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 = GetBcrypt(adminPassword) user.Password = tool.GetBcrypt(adminPassword)
user.Email = adminEmail user.Email = adminEmail
user.Phone = "" user.Phone = ""
user.Gender = USER_GENDER_UNKNOWN user.Gender = USER_GENDER_UNKNOWN
@ -379,7 +381,7 @@ func (this *InstallController) ValidateAdmin(writer http.ResponseWriter, request
this.PanicBadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail)) this.PanicBadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail))
} }
if !MatchBcrypt(adminPassword, existEmailUser.Password) { if !tool.MatchBcrypt(adminPassword, existEmailUser.Password) {
this.PanicBadRequest("邮箱或密码错误") this.PanicBadRequest("邮箱或密码错误")
} }
@ -423,11 +425,11 @@ func (this *InstallController) Finish(writer http.ResponseWriter, request *http.
this.PanicBadRequest(`请至少配置一名管理员`) this.PanicBadRequest(`请至少配置一名管理员`)
} }
var configItem = &ConfigItem{ var configItem = &config.ConfigItem{
//默认监听端口号 //默认监听端口号
ServerPort: CONFIG.ServerPort, ServerPort: config.CONFIG.ServerPort,
//上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter //上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter
MatterPath: CONFIG.MatterPath, MatterPath: config.CONFIG.MatterPath,
//mysql相关配置。 //mysql相关配置。
//数据库端口 //数据库端口
MysqlPort: mysqlPort, MysqlPort: mysqlPort,
@ -445,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 := GetConfPath() + "/tank.json" filePath := tool.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)
@ -454,7 +456,7 @@ func (this *InstallController) Finish(writer http.ResponseWriter, request *http.
this.PanicError(err) this.PanicError(err)
//通知配置文件安装完毕。 //通知配置文件安装完毕。
CONFIG.InstallOk() config.CONFIG.InstallOk()
//通知全局上下文,说系统安装好了 //通知全局上下文,说系统安装好了
CONTEXT.InstallOk() CONTEXT.InstallOk()

View File

@ -4,7 +4,9 @@ import (
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/nu7hatch/gouuid" "github.com/nu7hatch/gouuid"
"os" "os"
"tank/rest/config"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
"time" "time"
) )
@ -283,7 +285,7 @@ func (this *MatterDao) Delete(matter *Matter) {
this.PanicError(db.Error) this.PanicError(db.Error)
//从磁盘中删除该文件夹。 //从磁盘中删除该文件夹。
DeleteEmptyDir(matter.AbsolutePath()) tool.DeleteEmptyDir(matter.AbsolutePath())
} else { } else {
@ -363,7 +365,7 @@ func (this *MatterDao) Cleanup() {
db := CONTEXT.DB.Where("uuid is not null").Delete(Matter{}) db := CONTEXT.DB.Where("uuid is not null").Delete(Matter{})
this.PanicError(db.Error) this.PanicError(db.Error)
err := os.RemoveAll(CONFIG.MatterPath) err := os.RemoveAll(config.CONFIG.MatterPath)
this.PanicError(err) this.PanicError(err)
} }

View File

@ -1,6 +1,10 @@
package rest package rest
import "tank/rest/util" import (
"fmt"
"tank/rest/config"
"tank/rest/tool"
)
const ( const (
//根目录的uuid //根目录的uuid
@ -34,7 +38,7 @@ type Matter struct {
// set File's table name to be `profiles` // set File's table name to be `profiles`
func (Matter) TableName() string { func (Matter) TableName() string {
return TABLE_PREFIX + "matter" return config.TABLE_PREFIX + "matter"
} }
// 获取该Matter的绝对路径。path代表的是相对路径。 // 获取该Matter的绝对路径。path代表的是相对路径。
@ -44,7 +48,7 @@ func (this *Matter) AbsolutePath() string {
// 获取该Matter的MimeType // 获取该Matter的MimeType
func (this *Matter) MimeType() string { func (this *Matter) MimeType() string {
return util.GetMimeType(util.GetExtension(this.Name)) return tool.GetMimeType(tool.GetExtension(this.Name))
} }
@ -61,3 +65,20 @@ func NewRootMatter(user *User) *Matter {
return matter return matter
} }
//获取到用户文件的根目录。
func GetUserFileRootDir(username string) (rootDirPath string) {
rootDirPath = fmt.Sprintf("%s/%s/%s", config.CONFIG.MatterPath, username, MATTER_ROOT)
return rootDirPath
}
//获取到用户缓存的根目录。
func GetUserCacheRootDir(username string) (rootDirPath string) {
rootDirPath = fmt.Sprintf("%s/%s/%s", config.CONFIG.MatterPath, username, MATTER_CACHE)
return rootDirPath
}

View File

@ -6,8 +6,8 @@ import (
"os" "os"
"regexp" "regexp"
"strings" "strings"
"tank/rest/download"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
) )
/** /**
@ -64,7 +64,7 @@ func (this *MatterService) DownloadFile(
filename string, filename string,
withContentDisposition bool) { withContentDisposition bool) {
download.DownloadFile(writer, request, filePath, filename, withContentDisposition) tool.DownloadFile(writer, request, filePath, filename, withContentDisposition)
} }
//删除文件 //删除文件
@ -112,10 +112,10 @@ func (this *MatterService) Upload(file io.Reader, user *User, dirMatter *Matter,
fileRelativePath := dirRelativePath + "/" + filename fileRelativePath := dirRelativePath + "/" + filename
//创建父文件夹 //创建父文件夹
MakeDirAll(dirAbsolutePath) tool.MakeDirAll(dirAbsolutePath)
//如果文件已经存在了,那么直接覆盖。 //如果文件已经存在了,那么直接覆盖。
exist, err := PathExists(fileAbsolutePath) exist, err := tool.PathExists(fileAbsolutePath)
this.PanicError(err) this.PanicError(err)
if exist { if exist {
this.logger.Error("%s已经存在将其删除", fileAbsolutePath) this.logger.Error("%s已经存在将其删除", fileAbsolutePath)
@ -134,7 +134,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, HumanFileSize(fileSize)) this.logger.Info("上传文件 %s 大小为 %v ", filename, tool.HumanFileSize(fileSize))
//判断用户自身上传大小的限制。 //判断用户自身上传大小的限制。
if user.SizeLimit >= 0 { if user.SizeLimit >= 0 {
@ -143,7 +143,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 ", HumanFileSize(user.SizeLimit), HumanFileSize(fileSize))) panic(result.BadRequest("文件大小超出限制 %s > %s ", tool.HumanFileSize(user.SizeLimit), tool.HumanFileSize(fileSize)))
} }
} }
@ -234,7 +234,7 @@ func (this *MatterService) createDirectory(dirMatter *Matter, name string, user
relativePath := dirMatter.Path + "/" + name relativePath := dirMatter.Path + "/" + name
//磁盘中创建文件夹。 //磁盘中创建文件夹。
dirPath := MakeDirAll(absolutePath) dirPath := tool.MakeDirAll(absolutePath)
this.logger.Info("Create Directory: %s", dirPath) this.logger.Info("Create Directory: %s", dirPath)
//数据库中创建文件夹。 //数据库中创建文件夹。
@ -347,6 +347,9 @@ func (this *MatterService) AtomicMove(srcMatter *Matter, destDirMatter *Matter,
this.userService.MatterLock(srcMatter.UserUuid) this.userService.MatterLock(srcMatter.UserUuid)
defer this.userService.MatterUnlock(srcMatter.UserUuid) defer this.userService.MatterUnlock(srcMatter.UserUuid)
if destDirMatter == nil {
panic(result.BadRequest("destDirMatter cannot be nil."))
}
if !destDirMatter.Dir { if !destDirMatter.Dir {
this.PanicBadRequest("目标必须为文件夹") this.PanicBadRequest("目标必须为文件夹")
} }
@ -442,7 +445,7 @@ func (this *MatterService) copy(srcMatter *Matter, destDirMatter *Matter, name s
srcAbsolutePath := srcMatter.AbsolutePath() srcAbsolutePath := srcMatter.AbsolutePath()
//物理文件进行复制 //物理文件进行复制
CopyFile(srcAbsolutePath, destAbsolutePath) tool.CopyFile(srcAbsolutePath, destAbsolutePath)
//创建新文件的数据库信息。 //创建新文件的数据库信息。
newMatter := &Matter{ newMatter := &Matter{
@ -520,8 +523,8 @@ func (this *MatterService) AtomicRename(matter *Matter, name string, user *User)
//如果源是文件夹 //如果源是文件夹
oldAbsolutePath := matter.AbsolutePath() oldAbsolutePath := matter.AbsolutePath()
absoluteDirPath := GetDirOfPath(oldAbsolutePath) absoluteDirPath := tool.GetDirOfPath(oldAbsolutePath)
relativeDirPath := GetDirOfPath(matter.Path) relativeDirPath := tool.GetDirOfPath(matter.Path)
newAbsolutePath := absoluteDirPath + "/" + name newAbsolutePath := absoluteDirPath + "/" + name
//物理文件一口气移动 //物理文件一口气移动
@ -543,8 +546,8 @@ func (this *MatterService) AtomicRename(matter *Matter, name string, user *User)
//如果源是普通文件 //如果源是普通文件
oldAbsolutePath := matter.AbsolutePath() oldAbsolutePath := matter.AbsolutePath()
absoluteDirPath := GetDirOfPath(oldAbsolutePath) absoluteDirPath := tool.GetDirOfPath(oldAbsolutePath)
relativeDirPath := GetDirOfPath(matter.Path) relativeDirPath := tool.GetDirOfPath(matter.Path)
newAbsolutePath := absoluteDirPath + "/" + name newAbsolutePath := absoluteDirPath + "/" + name
//物理文件进行移动 //物理文件进行移动
@ -645,13 +648,10 @@ func (this *MatterService) AtomicCrawl(url string, filename string, user *User,
this.userService.MatterLock(user.Uuid) this.userService.MatterLock(user.Uuid)
defer this.userService.MatterUnlock(user.Uuid) defer this.userService.MatterUnlock(user.Uuid)
if url == "" || (!strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://")) { if url == "" || (!strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://")) {
panic("资源url必填并且应该以http://或者https://开头") panic("资源url必填并且应该以http://或者https://开头")
} }
//从指定的url下载一个文件。参考https://golangcode.com/download-a-file-from-a-url/ //从指定的url下载一个文件。参考https://golangcode.com/download-a-file-from-a-url/
resp, err := http.Get(url) resp, err := http.Get(url)
this.PanicError(err) this.PanicError(err)

View File

@ -3,6 +3,7 @@ package rest
import ( import (
"net/http" "net/http"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
) )
type PreferenceController struct { type PreferenceController struct {
@ -90,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 !MatchBcrypt(password, user.Password) { if !tool.MatchBcrypt(password, user.Password) {
this.PanicBadRequest("密码错误,不能执行!") this.PanicBadRequest("密码错误,不能执行!")
} }

View File

@ -1,5 +1,7 @@
package rest package rest
import "tank/rest/config"
type Preference struct { type Preference struct {
Base Base
Name string `json:"name" gorm:"type:varchar(45)"` Name string `json:"name" gorm:"type:varchar(45)"`
@ -12,5 +14,5 @@ type Preference struct {
// set File's table name to be `profiles` // set File's table name to be `profiles`
func (this *Preference) TableName() string { func (this *Preference) TableName() string {
return TABLE_PREFIX + "preference" return config.TABLE_PREFIX + "preference"
} }

View File

@ -7,8 +7,9 @@ import (
"net/http" "net/http"
"os" "os"
"strings" "strings"
"tank/rest/config"
"tank/rest/result" "tank/rest/result"
"tank/rest/util" "tank/rest/tool"
"time" "time"
) )
@ -70,7 +71,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 {
LOGGER.Error("错误: %v", err) tool.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 {
@ -106,7 +107,7 @@ func (this *Router) GlobalPanicHandler(writer http.ResponseWriter, request *http
} }
//错误情况记录。 //错误情况记录。
go SafeMethod(func() { go tool.SafeMethod(func() {
this.footprintService.Trace(writer, request, time.Now().Sub(startTime), false) this.footprintService.Trace(writer, request, time.Now().Sub(startTime), false)
}) })
} }
@ -130,7 +131,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
writer.Header().Set("Expires", "0") writer.Header().Set("Expires", "0")
if CONFIG.Installed { if config.CONFIG.Installed {
//已安装的模式 //已安装的模式
//统一处理用户的身份信息。 //统一处理用户的身份信息。
@ -155,7 +156,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} }
//正常的访问记录会落到这里。 //正常的访问记录会落到这里。
go SafeMethod(func() { go tool.SafeMethod(func() {
this.footprintService.Trace(writer, request, time.Now().Sub(startTime), true) this.footprintService.Trace(writer, request, time.Now().Sub(startTime), true)
}) })
@ -170,7 +171,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} else { } else {
//当作静态资源处理。默认从当前文件下面的static文件夹中取东西。 //当作静态资源处理。默认从当前文件下面的static文件夹中取东西。
dir := GetHtmlPath() dir := tool.GetHtmlPath()
requestURI := request.RequestURI requestURI := request.RequestURI
if requestURI == "" || request.RequestURI == "/" { if requestURI == "" || request.RequestURI == "/" {
@ -178,16 +179,16 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
} }
filePath := dir + requestURI filePath := dir + requestURI
exists, _ := PathExists(filePath) exists, _ := tool.PathExists(filePath)
if !exists { if !exists {
filePath = dir + "/index.html" filePath = dir + "/index.html"
exists, _ = PathExists(filePath) exists, _ = tool.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", util.GetMimeType(util.GetExtension(filePath))) writer.Header().Set("Content-Type", tool.GetMimeType(tool.GetExtension(filePath)))
diskFile, err := os.Open(filePath) diskFile, err := os.Open(filePath)
if err != nil { if err != nil {

View File

@ -1,6 +1,7 @@
package rest package rest
import ( import (
"tank/rest/config"
"time" "time"
) )
@ -13,5 +14,5 @@ type Session struct {
// set User's table name to be `profiles` // set User's table name to be `profiles`
func (this *Session) TableName() string { func (this *Session) TableName() string {
return TABLE_PREFIX + "session" return config.TABLE_PREFIX + "session"
} }

View File

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

View File

@ -1,4 +1,4 @@
package rest package tool
import ( import (
"errors" "errors"
@ -384,9 +384,11 @@ func (table *CacheTable) MostAccessed(count int64) []*CacheItem {
return r return r
} }
// 打印日志 // 打印日志
func (table *CacheTable) log(format string, v ...interface{}) { func (table *CacheTable) log(format string, v ...interface{}) {
LOGGER.Info(format, v...) //全局日志记录
//LOGGER.Info(format, v...)
} }
//新建一个缓存Table //新建一个缓存Table

View File

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

View File

@ -1,10 +1,11 @@
package rest package tool
//带有panic恢复的方法 //带有panic恢复的方法
func PanicHandler() { func PanicHandler() {
if err := recover(); err != nil { if err := recover(); err != nil {
LOGGER.Error("异步任务错误: %v", err) //TODO 全局日志记录
//LOGGER.Error("异步任务错误: %v", err)
} }
} }

View File

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

View File

@ -1,4 +1,4 @@
package rest package tool
import ( import (
"net/http" "net/http"
@ -33,14 +33,14 @@ func GetHostFromRequest(r *http.Request) string {
} }
//根据一个请求获取authenticationId //根据一个请求获取authenticationId
func GetSessionUuidFromRequest(request *http.Request) string { func GetSessionUuidFromRequest(request *http.Request, cookieAuthKey string) string {
//验证用户是否已经登录。 //验证用户是否已经登录。
sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) sessionCookie, err := request.Cookie(cookieAuthKey)
var sessionId string var sessionId string
if err != nil { if err != nil {
//从入参中捞取 //从入参中捞取
sessionId = request.FormValue(COOKIE_AUTH_KEY) sessionId = request.FormValue(cookieAuthKey)
} else { } else {
sessionId = sessionCookie.Value sessionId = sessionCookie.Value
} }

View File

@ -1,4 +1,4 @@
package rest package tool
import ( import (
"fmt" "fmt"
@ -215,22 +215,6 @@ func GetLogPath() string {
return filePath return filePath
} }
//获取到用户文件的根目录。
func GetUserFileRootDir(username string) (rootDirPath string) {
rootDirPath = fmt.Sprintf("%s/%s/%s", CONFIG.MatterPath, username, MATTER_ROOT)
return rootDirPath
}
//获取到用户缓存的根目录。
func GetUserCacheRootDir(username string) (rootDirPath string) {
rootDirPath = fmt.Sprintf("%s/%s/%s", CONFIG.MatterPath, username, MATTER_CACHE)
return rootDirPath
}
//复制文件 //复制文件
func CopyFile(srcPath string, destPath string) (nBytes int64) { func CopyFile(srcPath string, destPath string) (nBytes int64) {

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
package rest package rest
import ( import (
"tank/rest/config"
"time" "time"
) )
@ -17,5 +18,5 @@ type UploadToken struct {
} }
func (this *UploadToken) TableName() string { func (this *UploadToken) TableName() string {
return TABLE_PREFIX + "upload_token" return config.TABLE_PREFIX + "upload_token"
} }

View File

@ -4,7 +4,9 @@ import (
"net/http" "net/http"
"regexp" "regexp"
"strconv" "strconv"
"tank/rest/config"
"tank/rest/result" "tank/rest/result"
"tank/rest/tool"
"time" "time"
) )
@ -58,7 +60,7 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
this.PanicBadRequest("邮箱或密码错误") this.PanicBadRequest("邮箱或密码错误")
} else { } else {
if !MatchBcrypt(password, user.Password) { if !tool.MatchBcrypt(password, user.Password) {
this.PanicBadRequest("邮箱或密码错误") this.PanicBadRequest("邮箱或密码错误")
} }
@ -71,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: GetIpAddress(request), Ip: tool.GetIpAddress(request),
ExpireTime: expiration, ExpireTime: expiration,
} }
session.UpdateTime = time.Now() session.UpdateTime = time.Now()
@ -80,7 +82,7 @@ func (this *UserController) Login(writer http.ResponseWriter, request *http.Requ
//设置用户的cookie. //设置用户的cookie.
cookie := http.Cookie{ cookie := http.Cookie{
Name: COOKIE_AUTH_KEY, Name: config.COOKIE_AUTH_KEY,
Path: "/", Path: "/",
Value: session.Uuid, Value: session.Uuid,
Expires: expiration} Expires: expiration}
@ -88,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 = GetIpAddress(request) user.LastIp = tool.GetIpAddress(request)
this.userDao.Save(user) this.userDao.Save(user)
return this.Success(user) return this.Success(user)
@ -142,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: GetBcrypt(password), Password: tool.GetBcrypt(password),
Email: email, Email: email,
Phone: phone, Phone: phone,
Gender: gender, Gender: gender,
@ -215,7 +217,7 @@ func (this *UserController) Detail(writer http.ResponseWriter, request *http.Req
func (this *UserController) Logout(writer http.ResponseWriter, request *http.Request) *result.WebResult { func (this *UserController) Logout(writer http.ResponseWriter, request *http.Request) *result.WebResult {
//session置为过期 //session置为过期
sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) sessionCookie, err := request.Cookie(config.COOKIE_AUTH_KEY)
if err != nil { if err != nil {
return this.Success("已经退出登录了!") return this.Success("已经退出登录了!")
} }
@ -238,7 +240,7 @@ func (this *UserController) Logout(writer http.ResponseWriter, request *http.Req
expiration := time.Now() expiration := time.Now()
expiration = expiration.AddDate(-1, 0, 0) expiration = expiration.AddDate(-1, 0, 0)
cookie := http.Cookie{ cookie := http.Cookie{
Name: COOKIE_AUTH_KEY, Name: config.COOKIE_AUTH_KEY,
Path: "/", Path: "/",
Value: sessionId, Value: sessionId,
Expires: expiration} Expires: expiration}
@ -362,11 +364,11 @@ func (this *UserController) ChangePassword(writer http.ResponseWriter, request *
return this.Success(user) return this.Success(user)
} }
if !MatchBcrypt(oldPassword, user.Password) { if !tool.MatchBcrypt(oldPassword, user.Password) {
this.PanicBadRequest("旧密码不正确!") this.PanicBadRequest("旧密码不正确!")
} }
user.Password = GetBcrypt(newPassword) user.Password = tool.GetBcrypt(newPassword)
user = this.userDao.Save(user) user = this.userDao.Save(user)
@ -393,7 +395,7 @@ func (this *UserController) ResetPassword(writer http.ResponseWriter, request *h
user := this.userDao.CheckByUuid(userUuid) user := this.userDao.CheckByUuid(userUuid)
user.Password = GetBcrypt(password) user.Password = tool.GetBcrypt(password)
user = this.userDao.Save(user) user = this.userDao.Save(user)

View File

@ -1,6 +1,7 @@
package rest package rest
import ( import (
"tank/rest/config"
"time" "time"
) )
@ -44,7 +45,7 @@ type User struct {
// set User's table name to be `profiles` // set User's table name to be `profiles`
func (this *User) TableName() string { func (this *User) TableName() string {
return TABLE_PREFIX + "user" return config.TABLE_PREFIX + "user"
} }
//通过一个字符串获取性别 //通过一个字符串获取性别

View File

@ -2,6 +2,8 @@ package rest
import ( import (
"net/http" "net/http"
"tank/rest/config"
"tank/rest/tool"
"time" "time"
) )
@ -12,7 +14,7 @@ type UserService struct {
sessionDao *SessionDao sessionDao *SessionDao
//操作文件的锁。 //操作文件的锁。
locker *CacheTable locker *tool.CacheTable
} }
//初始化方法 //初始化方法
@ -31,7 +33,7 @@ func (this *UserService) Init() {
} }
//创建一个用于存储用户文件锁的缓存。 //创建一个用于存储用户文件锁的缓存。
this.locker = NewCacheTable() this.locker = tool.NewCacheTable()
} }
@ -76,7 +78,7 @@ func (this *UserService) bootstrap(writer http.ResponseWriter, request *http.Req
//登录身份有效期以数据库中记录的为准 //登录身份有效期以数据库中记录的为准
//验证用户是否已经登录。 //验证用户是否已经登录。
sessionCookie, err := request.Cookie(COOKIE_AUTH_KEY) sessionCookie, err := request.Cookie(config.COOKIE_AUTH_KEY)
if err != nil { if err != nil {
return return
} }