Finish all the i18n things of code.

This commit is contained in:
zicla
2019-05-06 02:18:08 +08:00
parent e37b248c8c
commit 54c5905a58
38 changed files with 504 additions and 720 deletions

View File

@ -6,7 +6,7 @@ import (
"golang.org/x/crypto/bcrypt"
)
//给密码字符串加密
//md5
func GetMd5(raw string) string {
return fmt.Sprintf("%x", md5.Sum([]byte(raw)))
}

View File

@ -6,7 +6,7 @@ import (
"strings"
)
//是否为win开发环境
//whether windows develop environment
func EnvWinDevelopment() bool {
ex, err := os.Executable()
@ -14,7 +14,7 @@ func EnvWinDevelopment() bool {
panic(err)
}
//如果exPath中包含了 \\AppData\\Local\\Temp 我们认为是在Win的开发环境中
//if exPath contains \\AppData\\Local\\Temp we regard as dev.
systemUser, err := user.Current()
if systemUser != nil {
@ -26,7 +26,7 @@ func EnvWinDevelopment() bool {
}
//是否为mac开发环境
//whether mac develop environment
func EnvMacDevelopment() bool {
ex, err := os.Executable()
@ -38,7 +38,7 @@ func EnvMacDevelopment() bool {
}
//是否为开发环境 (即是否在IDE中运行)
//whether develop environment (whether run in IDE)
func EnvDevelopment() bool {
return EnvWinDevelopment() || EnvMacDevelopment()

View File

@ -7,12 +7,12 @@ import (
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"runtime"
"strings"
)
//判断文件或文件夹是否已经存在
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
@ -26,14 +26,13 @@ func PathExists(path string) bool {
}
}
//获取GOPATH路径
func GetGoPath() string {
return build.Default.GOPATH
}
//获取开发时的Home目录
//get development home path.
func GetDevHomePath() string {
_, file, _, ok := runtime.Caller(0)
@ -50,8 +49,7 @@ func GetDevHomePath() string {
return dir
}
//获取该应用可执行文件的位置。
//例如C:\Users\lishuang\AppData\Local\Temp
//get home path for application.
func GetHomePath() string {
ex, err := os.Executable()
if err != nil {
@ -70,8 +68,9 @@ func GetHomePath() string {
return UniformPath(exPath)
}
//获取前端静态资源的位置。如果你在开发模式下可以将这里直接返回tank/build下面的html路径。
//例如C:/Users/lishuang/AppData/Local/Temp/html
//get html path
//dev: return $project/build/html
//prod: return $application/html
func GetHtmlPath() string {
//开发环境直接使用 build/html 下面的文件
@ -81,27 +80,27 @@ func GetHtmlPath() string {
return GetHomePath() + "/html"
}
//如果文件夹存在就不管,不存在就创建。 例如:/var/www/matter
//if directory not exit, create it.
func MakeDirAll(dirPath string) string {
exists := PathExists(dirPath)
if !exists {
//TODO:文件权限需要进一步考虑
err := os.MkdirAll(dirPath, 0777)
if err != nil {
panic("创建文件夹时出错!")
panic("error while creating directory")
}
}
return dirPath
}
//获取到一个Path的文件夹路径eg /var/www/xx.log -> /var/www
//eg /var/www/xx.log -> /var/www
func GetDirOfPath(fullPath string) string {
index1 := strings.LastIndex(fullPath, "/")
//可能是windows的环境
//maybe windows environment
index2 := strings.LastIndex(fullPath, "\\")
index := index1
if index2 > index1 {
@ -111,11 +110,11 @@ func GetDirOfPath(fullPath string) string {
return fullPath[:index]
}
//获取到一个Path 中的文件名,eg /var/www/xx.log -> xx.log
//get filename from path. eg /var/www/xx.log -> xx.log
func GetFilenameOfPath(fullPath string) string {
index1 := strings.LastIndex(fullPath, "/")
//可能是windows的环境
//maybe windows env
index2 := strings.LastIndex(fullPath, "\\")
index := index1
if index2 > index1 {
@ -125,17 +124,17 @@ func GetFilenameOfPath(fullPath string) string {
return fullPath[index+1:]
}
//尝试删除空文件夹 true表示删掉了一个空文件夹false表示没有删掉任何东西
//try to delete empty dir. true: delete an empty dir, false: delete nothing.
func DeleteEmptyDir(dirPath string) bool {
dir, err := ioutil.ReadDir(dirPath)
if err != nil {
panic(result.BadRequest("尝试读取目录%s时出错 %s", dirPath, err.Error()))
panic(result.BadRequest("occur error while reading %s %s", dirPath, err.Error()))
}
if len(dir) == 0 {
//空文件夹
//empty dir
err = os.Remove(dirPath)
if err != nil {
panic(result.BadRequest("删除磁盘上的文件夹%s出错 %s", dirPath, err.Error()))
panic(result.BadRequest("occur error while deleting %s %s", dirPath, err.Error()))
}
return true
}
@ -143,39 +142,23 @@ func DeleteEmptyDir(dirPath string) bool {
return false
}
//递归尝试删除空文件夹,一直空就一直删,直到不空为止
//delete empty dir recursive, delete until not empty.
func DeleteEmptyDirRecursive(dirPath string) {
fmt.Printf("递归删除删 %v \n", dirPath)
fmt.Printf("recursive delete %v \n", dirPath)
tmpPath := dirPath
for DeleteEmptyDir(tmpPath) {
dir := GetDirOfPath(tmpPath)
fmt.Printf("尝试删除 %v\n", dir)
fmt.Printf("try to delete %v\n", dir)
tmpPath = dir
}
}
//移除某个文件夹。
func RemoveDirectory(dirPath string) string {
exists := PathExists(dirPath)
if exists {
err := os.Remove(dirPath)
if err != nil {
panic("删除文件夹时出错!")
}
}
return dirPath
}
//获取配置文件存放的位置
//例如C:\Users\lishuang\AppData\Local\Temp/conf
//get conf path.
func GetConfPath() string {
homePath := GetHomePath()
@ -185,15 +168,14 @@ func GetConfPath() string {
if !exists {
err := os.MkdirAll(filePath, 0777)
if err != nil {
panic("创建日志文件夹时出错!")
panic("error while mkdir " + err.Error())
}
}
return filePath
}
//获取日志的路径
//例如:默认存放于 home/log
//get log path.
func GetLogPath() string {
homePath := GetHomePath()
@ -203,14 +185,14 @@ func GetLogPath() string {
if !exists {
err := os.MkdirAll(filePath, 0777)
if err != nil {
panic("创建日志文件夹时出错!")
panic("error while mkdir " + err.Error())
}
}
return filePath
}
//复制文件
//copy file
func CopyFile(srcPath string, destPath string) (nBytes int64) {
srcFileStat, err := os.Stat(srcPath)
@ -248,9 +230,12 @@ func CopyFile(srcPath string, destPath string) (nBytes int64) {
return nBytes
}
//路径归一化处理,把\\替换成/
func UniformPath(path string) string {
return strings.Replace(path, "\\", "/", -1)
//1. replace \\ to /
//2. clean path.
//3. trim suffix /
func UniformPath(p string) string {
p = strings.Replace(p, "\\", "/", -1)
p = path.Clean(p)
p = strings.TrimSuffix(p, "/")
return p
}

View File

@ -618,7 +618,7 @@ var allMimeMap = map[string]string{
".z": "application/x-compress",
".zip": "application/zip"}
//根据文件名字获取后缀名,均是小写。
//get extension by name. lowercase.
func GetExtension(filename string) string {
var extension = filepath.Ext(filename)
@ -627,7 +627,7 @@ func GetExtension(filename string) string {
}
//根据文件名字获取去除后缀的名称
//get filename without extension
func GetSimpleFileName(filename string) string {
for i := len(filename) - 1; i >= 0 && !os.IsPathSeparator(filename[i]); i-- {
@ -639,7 +639,7 @@ func GetSimpleFileName(filename string) string {
}
//根据一个后缀名获取MimeType获取不到默认返回 "application/octet-stream"
//get MimeType by filename, if not found return "application/octet-stream"
func GetMimeType(filename string) string {
extension := GetExtension(filename)
@ -651,7 +651,7 @@ func GetMimeType(filename string) string {
}
}
//根据一个后缀名获取MimeType获取不到默认返回fallback.
//get MimeType by filename, if not found return fallback.
func GetFallbackMimeType(filename string, fallback string) string {
extension := GetExtension(filename)

View File

@ -5,7 +5,7 @@ import (
"strings"
)
//根据一个请求获取ip.
//get ip from request
func GetIpAddress(r *http.Request) string {
var ipAddress string
@ -25,21 +25,21 @@ func GetIpAddress(r *http.Request) string {
return ipAddress
}
//根据一个请求获取host
func GetHostFromRequest(r *http.Request) string {
//get host from request
func GetHostFromRequest(request *http.Request) string {
return r.Host
return request.Host
}
//根据一个请求获取authenticationId
//get cookieAuthKey from request.
func GetSessionUuidFromRequest(request *http.Request, cookieAuthKey string) string {
//验证用户是否已经登录。
//get from cookie
sessionCookie, err := request.Cookie(cookieAuthKey)
var sessionId string
if err != nil {
//从入参中捞取
//try to get from Form
sessionId = request.FormValue(cookieAuthKey)
} else {
sessionId = sessionCookie.Value
@ -49,7 +49,7 @@ func GetSessionUuidFromRequest(request *http.Request, cookieAuthKey string) stri
}
//允许跨域请求
//allow cors.
func AllowCORS(writer http.ResponseWriter) {
writer.Header().Add("Access-Control-Allow-Origin", "*")
writer.Header().Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE")
@ -57,9 +57,9 @@ func AllowCORS(writer http.ResponseWriter) {
writer.Header().Add("Access-Control-Allow-Headers", "content-type")
}
//禁用缓存
//disable cache.
func DisableCache(writer http.ResponseWriter) {
//对于IE浏览器会自动缓存因此设置不缓存Header.
//IE browser will cache automatically. disable the cache.
writer.Header().Set("Pragma", "No-cache")
writer.Header().Set("Cache-Control", "no-cache")
writer.Header().Set("Expires", "0")

View File

@ -7,7 +7,6 @@ import (
"time"
)
//把一个大小转变成方便读的格式
//human readable file size
func HumanFileSize(bytes int64) string {
var thresh int64 = 1024
@ -33,7 +32,7 @@ func HumanFileSize(bytes int64) string {
return fmt.Sprintf("%s%s", numStr, units[u])
}
//获取MySQL的URL
//get mysql url.
func GetMysqlUrl(
mysqlPort int,
mysqlHost string,
@ -43,15 +42,15 @@ func GetMysqlUrl(
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local", mysqlUsername, mysqlPassword, mysqlHost, mysqlPort, mysqlSchema)
}
//获取四位随机数字
//get random number 4.
func RandomNumber4() string {
return fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31()%10000)
}
//获取四位随机数字
//get random 4 string
func RandomString4() string {
//0和ol和1难以区分剔除掉
//0 and o, 1 and l are not easy to distinguish
var letterRunes = []rune("abcdefghijkmnpqrstuvwxyz23456789")
r := rand.New(rand.NewSource(time.Now().UnixNano()))

View File

@ -5,57 +5,54 @@ import (
"time"
)
//将一个时间字符串转换成时间对象(yyyy-MM-dd HH:mm:ss)
//convert time string(yyyy-MM-dd HH:mm:ss) to Time object
func ConvertDateTimeStringToTime(timeString string) time.Time {
local, _ := time.LoadLocation("Local")
t, err := time.ParseInLocation("2006-01-02 15:04:05", timeString, local)
if err != nil {
panic(fmt.Sprintf("不能将%s转为时间类型", timeString))
panic(fmt.Sprintf("cannot convert %s to Time", timeString))
}
return t
}
//将一个时间字符串转换成日期时间对象(yyyy-MM-dd HH:mm:ss)
//convert Time object to string(yyyy-MM-dd HH:mm:ss)
func ConvertTimeToDateTimeString(time time.Time) string {
return time.Local().Format("2006-01-02 15:04:05")
}
//将一个时间字符串转换成日期时间对象(yyyy-MM-dd HH:mm:ss)
//convert Time object to string(HH:mm:ss)
func ConvertTimeToTimeString(time time.Time) string {
return time.Local().Format("15:04:05")
}
//将一个时间字符串转换成日期对象(yyyy-MM-dd)
//convert Time object to string(yyyy-MM-dd)
func ConvertTimeToDateString(time time.Time) string {
return time.Local().Format("2006-01-02")
}
//一天中的最后一秒钟
func LastSecondOfDay(day time.Time) time.Time {
local, _ := time.LoadLocation("Local")
return time.Date(day.Year(), day.Month(), day.Day(), 23, 59, 59, 0, local)
}
//一天中的第一秒钟
func FirstSecondOfDay(day time.Time) time.Time {
local, _ := time.LoadLocation("Local")
return time.Date(day.Year(), day.Month(), day.Day(), 0, 0, 0, 0, local)
}
//一天中的第一分钟
func FirstMinuteOfDay(day time.Time) time.Time {
local, _ := time.LoadLocation("Local")
return time.Date(day.Year(), day.Month(), day.Day(), 0, 1, 0, 0, local)
}
//明天此刻的时间
//Tomorrow right now
func Tomorrow() time.Time {
tomorrow := time.Now()
tomorrow = tomorrow.AddDate(0, 0, 1)
return tomorrow
}
//昨天此刻的时间
//Yesterday right now
func Yesterday() time.Time {
tomorrow := time.Now()
tomorrow = tomorrow.AddDate(0, 0, -1)

View File

@ -4,23 +4,20 @@ import (
"archive/zip"
"github.com/eyebluecn/tank/code/tool/result"
"io"
"log"
"os"
"path/filepath"
"strings"
)
//srcPath压缩到destPath。
//zip srcPath to destPath。
func Zip(srcPath string, destPath string) error {
//统一处理\\成/
srcPath = UniformPath(srcPath)
if PathExists(destPath) {
panic(result.BadRequest("%s 已经存在了", destPath))
panic(result.BadRequest("%s exits", destPath))
}
// 创建准备写入的文件
fileWriter, err := os.Create(destPath)
if err != nil {
return err
@ -32,53 +29,44 @@ func Zip(srcPath string, destPath string) error {
}
}()
// 通过 fileWriter 来创建 zip.Write
zipWriter := zip.NewWriter(fileWriter)
defer func() {
// 检测一下是否成功关闭
if err := zipWriter.Close(); err != nil {
log.Fatalln(err)
panic(err)
}
}()
//上一个文件夹路径
baseDirPath := GetDirOfPath(srcPath) + "/"
// 下面来将文件写入 zipWriter ,因为有可能会有很多个目录及文件,所以递归处理
err = filepath.Walk(srcPath, func(path string, fileInfo os.FileInfo, errBack error) (err error) {
if errBack != nil {
return errBack
}
//统一处理\\成/
path = UniformPath(path)
// 通过文件信息,创建 zip 的文件信息
fileHeader, err := zip.FileInfoHeader(fileInfo)
if err != nil {
return
}
// 替换文件信息中的文件名
fileHeader.Name = strings.TrimPrefix(path, baseDirPath)
// 目录前要加上/
// directory need /
if fileInfo.IsDir() {
fileHeader.Name += "/"
}
// 写入文件信息,并返回一个 Write 结构
writer, err := zipWriter.CreateHeader(fileHeader)
if err != nil {
return
}
// 检测,如果不是标准文件就只写入头信息,不写入文件数据到 writer
// 如目录,也没有数据需要写
//only regular has things to write.
if !fileHeader.Mode().IsRegular() {
return nil
}
// 打开要压缩的文件
fileToBeZip, err := os.Open(path)
defer func() {
err = fileToBeZip.Close()
@ -90,7 +78,6 @@ func Zip(srcPath string, destPath string) error {
return
}
// 将打开的文件 Copy 到 writer
_, err = io.Copy(writer, fileToBeZip)
if err != nil {
return