util

package
v0.0.0-...-1fceeaa Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2019 License: MIT Imports: 36 Imported by: 4

Documentation

Index

Constants

View Source
const (
	WelCome = `` /* 214-byte string literal not displayed */

	ViewErrorMsg = `
		<center>
		<h2>访问出错</h2>
		<h3>提示:{{.ErrorMsg}}</h3>
		</center>
	`
)
View Source
const (
	CodeSysError       = 1000
	CodeSysBusy        = 1001
	CodeParamError     = 2000
	CodeBizFailure     = 2001
	CodeIllegalRequest = 2002
	CodeNoLogin        = 2003
	CodeNoAuth         = 2004
	CodeToHome         = 3000
	CodeToResetPwd     = 3001

	MsgSysError   = "抱歉,此功能故障,请联系技术人员"
	MsgSysBusy    = "抱歉,服务器繁忙,请稍后重试"
	MsgParamError = "参数不符合接口要求,请检查字段类型、嵌套结构的格式等"
	MsgNoLogin    = "请先登录"
	MsgNoAuth     = "抱歉,您的角色没有此功能的操作权限,请联系技术人员"
)

Variables

View Source
var (
	Exists500File = false
)

Functions

func BizExceptionHandler

func BizExceptionHandler(biz BizException, ctx iris.Context)

func BizExceptionViewHandler

func BizExceptionViewHandler(biz BizException, ctx iris.Context)

func CheckPwdStr

func CheckPwdStr(input string, store string) bool

func CheckRst

func CheckRst(p *gorm.DB)

func CloseDbConnection

func CloseDbConnection(db *gorm.DB, isBegin *bool)

func ConsoleError

func ConsoleError(content string)

*

  • 打印错误日志到控制台,支持颜色
  • @param content 日志内容

func ConvertToByte

func ConvertToByte(src *string, srcCode string, targetCode string) []byte

func CutArrayString

func CutArrayString(arr []string, per int) [][]string

*

  • 大数组分割成多个小数组 - 用于批量处理数据的时候,防止SQL参数过大
  • @param arr 大数组
  • @param per 每个小数组的长度
  • @return 小数组

func CutArrayUint64

func CutArrayUint64(arr []uint64, per int) [][]uint64

*

  • 大数组分割成多个小数组 - 用于批量处理数据的时候,防止SQL参数过大
  • @param arr 大数组
  • @param per 每个小数组的长度
  • @return 小数组

func DealFileName

func DealFileName(fileName string) string

*

  • 处理文件名中特殊的字符,将特殊字符转换成下划线
  • @param fileName 旧文件名
  • @return 转换后的文件名(只是字符串处理,并非正真修改文件名)

func DeleteCache

func DeleteCache(key string)

*

  • 删除缓存
  • @param key 缓存key

func DeleteHard

func DeleteHard(db *gorm.DB, table, where string, value ...interface{})

func DownloadZipFileFromCamp

func DownloadZipFileFromCamp(zipName string, dir []string, files []map[string]string) string

*

  • 从FileCamp服务器上指定的文件夹下打包
  • @param filePath 文件路径(相对项目,比如:2019_10_02/uuid.txt)
  • @return 预览地址(相对路径,需要前端拼上服务器地址才完整)

func EncryptPwdStr

func EncryptPwdStr(input string) string

func ExpireCache

func ExpireCache(key string, lifetime time.Duration) error

*

  • 设置过期时间
  • @param key 缓存key
  • @param lifetime 新的有效时间(秒)
  • @return 设置过程发生的错误

func GetCache

func GetCache(key string, data interface{}) error

*

  • 获取缓存数据
  • @param key 缓存key
  • @param data 预期的数据体(结构体、map等类型)
  • @return 取值过程发生的错误,或json字符串解析成预期格式出错

func GetCurrentPath

func GetCurrentPath() string

*

  • 获取当前运行路径

func GetDbConnectionName

func GetDbConnectionName(name []string) string

func GetFileDownloadPath

func GetFileDownloadPath(fileName, filePath string) string

*

  • 获取文件下载路径
  • @param fileName 原始文件名称(一般都是中文)
  • @param filePath 文件路径(相对项目,比如:2019_10_02/uuid.txt)
  • @return 下载地址(相对路径,需要前端拼上服务器地址才完整)

func GetFilePreviewPath

func GetFilePreviewPath(filePath string) string

*

  • 获取文件预览路径(通过调预览服务器获得)
  • @param filePath 文件路径(相对项目,比如:2019_10_02/uuid.txt)
  • @return 预览地址(相对路径,需要前端拼上服务器地址才完整)

func GetFileSize

func GetFileSize(filePath string) (int64, bool)

*

  • 读取文件大小
  • @param filePath 文件路径
  • @return int64 文件大小
  • @return bool 是否读取成功

func GetTotal

func GetTotal(db *gorm.DB) int

func GetUidByTokenInSession

func GetUidByTokenInSession(res http.ResponseWriter, req *http.Request) uint64

func InArrayString

func InArrayString(elem string, arr []string) bool

*

  • 判断目标值是否在字符串数组中
  • @param elem 目标值
  • @param arr 字符串数组

func InArrayUint64

func InArrayUint64(elem uint64, arr []uint64) bool

*

  • 判断目标值ID是否在枚举值数组中
  • @param elem 目标值
  • @param arr uint64数组

func InArrayUint8

func InArrayUint8(elem uint8, arr []uint8) bool

*

  • 判断目标值是否在枚举值数组中
  • @param elem 目标值
  • @param arr uint8数组

func IsEmpty

func IsEmpty(p interface{}) bool

func IsExistDir

func IsExistDir(dirPath string) (bool, error)

*

  • 目录是否存在
  • @param dirPath 文件路径
  • @return bool 目录是否存在
  • @return error 目录存在或不存在时,返回nil;如果目标是非目录或无法读取目标的状态,则返回具体错误信息

func IsExistFile

func IsExistFile(filePath string) (bool, error)

*

  • 文件是否存在
  • @param filePath 文件路径
  • @return bool 文件是否存在
  • @return error 文件存在或不存在时,返回nil;如果目标是目录或无法读取目标的状态,则返回具体错误信息

func JsonResponse

func JsonResponse(j *JsonData, ctx iris.Context)

func LogError

func LogError(msg string, data interface{})

*

  • 写日志 - Error类
  • @param msg 日志标题
  • @param data 日志内容(复杂数据类型转换成JSON格式输出)

func LogException

func LogException(msg string)

*

  • 写日志 - 异常类(Error类型,堆栈信息作为日志内容)
  • @param msg 日志标题

func LogInfo

func LogInfo(msg string, data interface{})

*

  • 写日志 - Info类
  • @param msg 日志标题
  • @param data 日志内容(复杂数据类型转换成JSON格式输出)

func Match

func Match(pattern string, str string) bool

func MkDir

func MkDir(dirPath string) error

*

  • 创建目录(如果目录存在时,不做任何处理)
  • @param dirPath 文件路径
  • @return error 创建文件过程发生的错误

func MkFile

func MkFile(filePath string) error

*

  • 创建空文件(并关闭文件,如果文件存在时,不做任何处理)
  • @param filePath 文件路径
  • @return error 创建文件过程发生的错误

func NotFoundHandler

func NotFoundHandler(ctx iris.Context)

func OpenDbConnection

func OpenDbConnection(name ...string) *gorm.DB

func OpenFile

func OpenFile(filePath string) *os.File

*

  • 打开文件,没有则创建
  • @param filePath 文件路径(相对或绝对)

func RandomNumber

func RandomNumber(length int) string

func RandomStr

func RandomStr(length int) string

func ReadFile

func ReadFile(path string) ([]byte, bool)

*

  • 读取文件的内容(一次性读取完)

func ReadLine

func ReadLine(fileName string, handler func(string))

*

  • 逐行读取文件内容
  • @param fileName 文件路径
  • @param handler 回调方法,传入一行文件内容

func Replace

func Replace(str *string, old string, new string) string

func Round

func Round(f float64) float64

*

  • 保留两位小数

func SendMail

func SendMail(viewData map[string]string, view, title, to, toName string, e bool) bool

发送邮件

func SendSms

func SendSms(mobiles []string, code string, templateData map[string]interface{}) bool

*

  • 发送短信 - 通过msgRouter服务转发
  • @param mobiles 手机号数组
  • @param code 短信模板名称
  • @param templateData 模板参数

func SetCache

func SetCache(key string, value interface{}, lifetime time.Duration) error

*

  • 设置缓存数据
  • @param key 缓存key
  • @param value 数据,将自动转成JSON存储
  • @param lifetime 有效时间(秒),0表示永久缓存
  • @return 存储缓存过程发生的错误

func SetDefaultRedisClient

func SetDefaultRedisClient(client *redis.Client)

func SetPage

func SetPage(db *gorm.DB, skip int, take int) *gorm.DB

func SnakeString

func SnakeString(s string) string

func Split

func Split(str *string, sep string) []string

func StartSchedules

func StartSchedules()

开始执行任务

func StrCut

func StrCut(str string, length int) string

func StrLL

func StrLL(str *string, subStr string) string

func StrLR

func StrLR(str *string, subStr string) string

func StrRL

func StrRL(str *string, subStr string) string

func StrRR

func StrRR(str *string, subStr string) string

func Substr

func Substr(str *string, start int, length ...int) string

func SysExceptionHandler

func SysExceptionHandler(ctx iris.Context)

func SysExceptionViewHandler

func SysExceptionViewHandler(ctx iris.Context)

func ThrowBiz

func ThrowBiz(msg string, code ...int)

*

  • 抛出业务失败的异常
  • @param msg 错误提示信息
  • @param code 非必传,错误码

func ThrowSys

func ThrowSys(msg string, data ...interface{})

*

  • 抛出系统异常提示,并记录日志
  • @param msg 日志的标题
  • @param data 非必传,日志内容

func ToMap

func ToMap(m interface{}, filter []string) map[string]interface{}

func UniqueArrayString

func UniqueArrayString(arr []string) []string

*

  • 字符串数组去重 - 用于ID数组去重
  • @param arr 字符串数组

func UniqueArrayUint64

func UniqueArrayUint64(arr []uint64) []uint64

*

  • 整型数组去重 - 用于ID数组去重 todo:排序错乱
  • @param arr 字符串数组

func UnixTimeToMdHi

func UnixTimeToMdHi(ut int64) string

*

  • 时间戳转成易读格式:x月x日 时:分

func UploadFileMoveToLocal

func UploadFileMoveToLocal(fileInfo UploadFile) string

*

  • 上传文件后,将本地临时目录文件迁移至本地正式目录
  • @param fileInfo 文件上传回调对象
  • @return 正式目录文件路径(可直接用于保存在数据库中)

func UploadFileMoveWithFileCamp

func UploadFileMoveWithFileCamp(fileInfo []UploadFile, token string, ip string) string

*

  • 将临时存储的文件迁移到正式目录(支持FTP方式)
  • @return fileCamp服务器上目录存储的日期,将【日期值+'/'+uuid.ext】这串保存到数据库中即可

func UploadFilePathForCamp

func UploadFilePathForCamp(fileInfo UploadFile, date string) string

*

  • 拼接文件名
  • @return 从fileCamp服务器返回的日期+文件uuid和后缀,可将此值直接保存到数据库

func Uuid

func Uuid() string

func VerifyCodeCheck

func VerifyCodeCheck(db *gorm.DB, userId uint64, code string, currTime int64)

func VerifyCodeDeal

func VerifyCodeDeal(db *gorm.DB, userId string)

func ZipByCommand

func ZipByCommand(fileName string, files string) error

压缩目录(命令行)

Types

type Api

type Api struct {
	Login      bool
	AuthKey    string
	Controller func(base *Base) ApiInterface
}

type ApiInterface

type ApiInterface interface {
	Handler() int
}

type Base

type Base struct {

	// http对象和常用属性
	Ctx    iris.Context
	Method string
	Path   string

	// 请求时间
	Time      time.Time
	TimeStamp int64

	// 分页参数
	Page     int
	PageSize int
	Skip     int

	// 默认数据库连接
	DB *gorm.DB

	// 会话数据
	Session  *Session
	MyId     uint64
	MyDeptId uint64

	// Json响应
	ResData *JsonData
	IsView  bool
	// contains filtered or unexported fields
}

*

  • 接口结构体中包含的Base子结构体,提供了各种业务结构需要的数据和方法

func NewBaseApi

func NewBaseApi(needLogin bool, ctx iris.Context) *Base

*

  • 控制器中创建Base对象,然后传入业务接口中

func (*Base) Begin

func (this *Base) Begin()

*

  • 默认数据库连接,开启事务

func (*Base) CloseConnection

func (this *Base) CloseConnection()

*

  • 关闭默认数据库连接

func (*Base) Commit

func (this *Base) Commit()

*

  • 默认数据库连接,提交事务

func (*Base) DeleteHard

func (this *Base) DeleteHard(table, where string, value ...interface{})

*

  • 硬删数据
  • 当模型中有DeleteAt字段时,调DB.Delete是软删,而非硬删,因此业务需要硬删时,需要调此方法来物理删除
  • 该方法已经校验了SQL执行过程中出现的异常 *
  • @param table 表名
  • @param where 筛选子句,可以使用占位符
  • @param value 筛选子句,代替占位符的值

func (*Base) Error

func (this *Base) Error(msg string, code ...int) int

*

  • Json响应 - 业务失败
  • @param msg 业务提示信息
  • @param code 非必传参数,业务CODE,默认为 CodeBizFailure
  • @return 框架响应类型:JSON

func (*Base) GetIp

func (this *Base) GetIp() string

*

  • 获取当前访问用户的IP地址

func (*Base) GetTotal

func (this *Base) GetTotal(obj *gorm.DB) int

*

  • 查询当前DB对象的列表总数
  • @param obj DB对象:一般已经指定了表名、过滤条件;没有指定分页、排序、查询列

func (*Base) HasAuth

func (this *Base) HasAuth(authKey string) bool

*

  • 校验当前登录人是否拥有某个权限
  • @param authKey 被校验的权限KEY
  • @return 是否有无此权限

func (*Base) Init

func (this *Base) Init(data interface{})

*

  • 业务接口初始化Base对象的方法,并处理请求参数
  • 规范:在业务接口的New方法中调用,且每次请求只能调用一次,调用格式如下:
  • this.Base = this.Init(ctx, this)

func (*Base) OpenConnection

func (this *Base) OpenConnection()

*

  • 开启默认数据库连接

func (*Base) QueryPageList

func (this *Base) QueryPageList(obj *gorm.DB, data interface{})

*

  • 查询当前分页数据
  • @param obj DB对象,在total的DB对象基础上,已经处理了查询列、排序,无需指定分页
  • @data interface{} 任意类型的数组或切片结构,外边需要传入指针

func (*Base) RollBack

func (this *Base) RollBack()

*

  • 默认数据库连接,回滚事务

func (*Base) SetViewResponse

func (this *Base) SetViewResponse()

*

  • 设置本次响应类型为视图,错误处理结果也相应的自动转换成HTML

func (*Base) Success

func (this *Base) Success(msg string) int

*

  • Json响应 - 业务成功
  • @param msg 异常日志的标题
  • @return 框架响应类型:JSON

func (*Base) SuccessWithData

func (this *Base) SuccessWithData(data interface{}, msg ...string) int

*

  • Json响应 - 业务成功,并附带数据体
  • @param data 数据体,任意类型的数据(公有属性才可以转成JSON数据)
  • @param msg 提示信息,非必传,默认为 "成功"
  • @return 框架响应类型:JSON

func (*Base) SuccessWithList

func (this *Base) SuccessWithList(list interface{}, total int) int

*

  • Json响应 - 业务成功,并返回列表数据
  • @param list 列表数据,任意类型的数据(列表中的公有属性才可以转成JSON数据)
  • @param total 总数
  • @return 框架响应类型:JSON

func (*Base) View

func (this *Base) View(viewName string) int

*

  • 视图响应 - 业务成功,并返回指定的视图文件,相对于 ./view目录
  • @param viewName 视图名称
  • @return 框架响应类型:视图

type BizException

type BizException struct {
	Msg  string
	Code int
}

type JsonData

type JsonData struct {
	// contains filtered or unexported fields
}

func JsonCustom

func JsonCustom(msg string, data interface{}, code int) *JsonData

func JsonError

func JsonError(msg string, code int) *JsonData

func JsonSuccess

func JsonSuccess(msg string) *JsonData

func JsonSuccessWithData

func JsonSuccessWithData(data interface{}, msg string) *JsonData

func JsonSuccessWithList

func JsonSuccessWithList(list interface{}, total int) *JsonData

type Service

type Service struct {
	ResponseData string
	StatusCode   int
	// contains filtered or unexported fields
}

*

  • 发送Http/Https的Server组件 *
  • host 主机(协议://IP:端口号)
  • path 请求路由
  • formData 请求参数
  • bodyData 请求body
  • ResponseData 响应数据
  • StatusCode 响应状态码
  • validTls 是否启用tls证书
  • tls tls证书
  • cookie 会话数据

func NewService

func NewService(host string, path string) *Service

*

  • 创建Server组件对象
  • @param host 主机(协议://IP:端口号)
  • @param path 路由
  • @return Server组件对象

func (*Service) AddFormData

func (this *Service) AddFormData(key string, value string)

*

  • 添加请求参数(formData)
  • @param key 键
  • @param value 值

func (*Service) AddFormDataForJson

func (this *Service) AddFormDataForJson(key string, data interface{})

*

  • 将指定参数转成JSON,并作为一个参数

func (*Service) Body

func (this *Service) Body(code200 ...bool) error

*

  • 发起BodyJson请求
  • @param code200 请求码200才算正确请求,其他状态码都一律以错误处理,默认为false
  • @return 如果请求发生错误,返回error对象

func (*Service) ClearParam

func (this *Service) ClearParam()

*

  • 清空请求参数

func (*Service) Get

func (this *Service) Get(code200 ...bool) error

*

  • 发起Get请求
  • @param code200 请求码200才算正确请求,其他状态码都一律以错误处理,默认为false
  • @return 如果请求发生错误,返回error对象

func (*Service) LogError

func (this *Service) LogError(msg string)

*

  • 通过组件的错误日志方式,记录请求和响应对象

func (*Service) Post

func (this *Service) Post(code200 ...bool) error

*

  • 发起Post请求
  • @param code200 请求码200才算正确请求,其他状态码都一律以错误处理,默认为false
  • @return 如果请求发生错误,返回error对象

func (*Service) SetBodyData

func (this *Service) SetBodyData(bodyData string)

*

  • 设置请求参数(bodyData)
  • @param bodyData 请求参数

func (*Service) SetBodyDataForJson

func (this *Service) SetBodyDataForJson(bodyData interface{})

*

  • 设置请求参数,自动转成JSON格式(bodyData)
  • @param bodyData 请求参数

func (*Service) SetCookie

func (this *Service) SetCookie(jar *cookiejar.Jar)

*

  • 设置会话对象
  • @param jar 会话对象

func (*Service) SetFormData

func (this *Service) SetFormData(formData *map[string]string)

*

  • 设置请求参数(formData)
  • @param formData 请求参数

func (*Service) SetHost

func (this *Service) SetHost(host string)

*

  • 设置服务地址
  • @param host 主机(协议://IP:端口号)

func (*Service) SetPath

func (this *Service) SetPath(path string)

*

  • 设置请求路由
  • @param path 请求路由

func (*Service) SetTls

func (this *Service) SetTls(tls *http.Transport)

*

  • 设置TLS对象,并启用证书请求服务
  • @param tls tls对象

func (*Service) ToJson

func (this *Service) ToJson(data interface{}) bool

*

  • 将响应数据转成json

type Session

type Session struct {
	// contains filtered or unexported fields
}

*

  • 某个请求生命周期内,业务逻辑的会话数据结构

func NewSession

func NewSession(needLogin bool, token string) *Session

*

  • 接收到请求后调此方法,为接口生成本次请求的会话数据

func (*Session) AddDeviceList

func (s *Session) AddDeviceList(uId string)

func (*Session) All

func (s *Session) All() SessionData

func (*Session) ClearData

func (s *Session) ClearData()

func (*Session) Get

func (s *Session) Get(key string) interface{}

*

  • 获取用户信息中指定key的值
  • @param key 用户信息的某个字段
  • @return 用户信息的某个字段的值

func (*Session) GetKey

func (s *Session) GetKey() string

func (*Session) GetToken

func (s *Session) GetToken() string

func (*Session) GetUserAuth

func (s *Session) GetUserAuth() []string

func (*Session) GetUserData

func (s *Session) GetUserData() map[string]interface{}

func (*Session) GetUserRoles

func (s *Session) GetUserRoles() []string

func (*Session) IsChanged

func (s *Session) IsChanged() bool

func (*Session) IsLogged

func (s *Session) IsLogged() bool

func (*Session) IsNeedLogin

func (s *Session) IsNeedLogin() bool

func (*Session) RemoveDeviceList

func (s *Session) RemoveDeviceList(uId string, key string)

func (*Session) Set

func (s *Session) Set(key string, value interface{})

*

  • 设置或新增用户信息的某个字段和值
  • @param key 字段名
  • @param value 字段值

func (*Session) SignIn

func (s *Session) SignIn(uIdField string, user map[string]interface{}, auth, roles []string)

*

  • 注册会话
  • @param uIdField 用户ID字段名,一般都是"UserId"
  • @param user 用户信息map结构
  • @param auth 权限key的集合
  • @param roles 角色Id的集合

func (*Session) SignOut

func (s *Session) SignOut()

func (*Session) UpdateSession

func (s *Session) UpdateSession()

type SessionData

type SessionData struct {
	// 是否已经登录
	Flag bool

	// 用户信息
	User map[string]interface{}

	// 拥有的权限key的集合
	Auth []string

	// 所属角色id的集合
	Roles []string
}

*

  • 存储在redis中的某个用户的会话数据结构

type SysException

type SysException struct {
	Msg  string
	Code int
}

type TimerData

type TimerData struct {
	// contains filtered or unexported fields
}

func NewSchedule

func NewSchedule(handler func()) *TimerData

设置定时任务

func (*TimerData) DailyAt

func (t *TimerData) DailyAt(hour int, minute int)

每天的x时x分

  • hour: [0, 23]
  • minute: [0,59]

func (*TimerData) EveryFiveMinutes

func (t *TimerData) EveryFiveMinutes()

每五分钟

func (*TimerData) EveryMinute

func (t *TimerData) EveryMinute()

每分钟

func (*TimerData) EveryTenMinutes

func (t *TimerData) EveryTenMinutes()

每十分钟

func (*TimerData) EveryThirtyMinutes

func (t *TimerData) EveryThirtyMinutes()

每半小时

func (*TimerData) HourlyAt

func (t *TimerData) HourlyAt(minute int)

每小时的x分

  • minute: [0,59]

func (*TimerData) MonthlyAt

func (t *TimerData) MonthlyAt(day int, hour int, minute int)

每月的x日x时x分

  • day: [1,31]
  • hour: [0, 23]
  • minute: [0,59]

func (*TimerData) SetRepeat

func (t *TimerData) SetRepeat(repeat bool) *TimerData

设置是否重复,默认不重复,如果不重复的话,在周期内该函数尚未执行完毕,则此周期就不再执行

func (*TimerData) WeeklyAt

func (t *TimerData) WeeklyAt(week int, hour int, minute int)

每周的星期几x时x分

  • week: [0,6] (0表示星期天)
  • hour: [0, 23]
  • minute: [0,59]

func (*TimerData) YearlyAt

func (t *TimerData) YearlyAt(month int, day int, hour int, minute int)

每年的x月x日x时x分

  • month: [1,12]
  • day: [1,31]
  • hour: [0, 23]
  • minute: [0,59]

type UploadFile

type UploadFile struct {
	Name string
	Ext  string
	Type string
	Size int64
	Id   string
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL