Documentation
¶
Overview ¶
Package utils 是一个将开发中常用的通用类函数封装统一存放在这里以便复用的函数工具包
Index ¶
- Variables
- func AnonymousName(ctx context.Context, serviceid int, ip, ua string, prefixs ...string) string
- func AvgFloat64(f []float64) (float64, error)
- func CheckPasswordHash(password, hash string) bool
- func ChunkFloat64Slice(data []float64, chunkSize int) [][]float64
- func CloseRedisInstances()
- func CopyFile(sourceFile, destinationFile string) (err error)
- func GetGoCache(c *cache.Cache, key string, resultPointer interface{}) error
- func GetLatestTradingDay() string
- func GetLocalIP() (string, error)
- func HTTPGET(ctx context.Context, cli *http.Client, apiurl string, header map[string]string, ...) error
- func HTTPGETRaw(ctx context.Context, cli *http.Client, apiurl string, header map[string]string) ([]byte, error)
- func HTTPPOST(ctx context.Context, cli *http.Client, req *http.Request, ...) error
- func HTTPPOSTRaw(ctx context.Context, cli *http.Client, req *http.Request) ([]byte, error)
- func HashPassword(password string) (string, error)
- func InitViper(configFile string, onConfigChangeRun func(fsnotify.Event)) error
- func IntHashDecode(s string, salt string, minLength int, prefix string) int
- func IntHashEncode(i int, salt string, minLength int, prefix string) string
- func IntsMinMax(ints ...int) (min int, max int)
- func IsEmailValid(email string) bool
- func IsEqualStringSlice(s1, s2 []string) bool
- func IsInitedViper() bool
- func IsIntInSlice(i int, s []int) bool
- func IsStrInSlice(i string, s []string) bool
- func IsTradingDay() bool
- func JaccardSimilarity(s1, s2 []interface{}) float64
- func MD5(v string) string
- func MapIntIntSortedKeys(m map[int]int, desc bool) []int
- func MapStrIntSortedKeys(m map[string]int, desc bool) []string
- func MidValueFloat64(values []float64) (float64, error)
- func NewHTTPGetURLWithQueryString(ctx context.Context, apiurl string, params map[string]string) (string, error)
- func NewHTTPJSONReq(ctx context.Context, apiurl string, reqData interface{}) (*http.Request, error)
- func NewHTTPMultipartReq(ctx context.Context, apiurl string, reqData map[string]string) (*http.Request, error)
- func NewRedisClient(opt *redis.Options) (*redis.Client, error)
- func NewRedisClusterClient(opt *redis.ClusterOptions) (*redis.ClusterClient, error)
- func NewRedisFailoverClient(opt *redis.FailoverOptions) (*redis.Client, error)
- func RedisClient(which string) (*redis.Client, error)
- func RedisClusterClient(which string) (*redis.ClusterClient, error)
- func RedisSentinelClient(which string) (*redis.Client, error)
- func RemoveAllWhitespace(s string) string
- func RemoveDuplicateWhitespace(s string, trim bool) string
- func RemoveStringSliceItemByIndex(slice []string, index int) []string
- func RequestHTTPHandler(app http.Handler, method, path string, body []byte, header map[string]string) (*httptest.ResponseRecorder, error)
- func RequestHTTPHandlerFunc(f http.HandlerFunc, method string, body []byte, header map[string]string) ([]byte, error)
- func ReverseFloat64Slice(numbers []float64)
- func ReverseString(s string) string
- func ReversedFloat64Slice(numbers []float64) []float64
- func SetRedisInstances(which string, rdb *redis.Client) error
- func SplitStringFields(s string) []string
- func StdDeviationFloat64(fs []float64) (float64, error)
- func StrSimilarity(s1, s2 string, algorithm string) float64
- func StrToTime(layout, value string, loc ...*time.Location) (time.Time, error)
- func StructTagList(item interface{}, tag string) []string
- func StructToMap(item interface{}, tag string) map[string]interface{}
- func StructToURLValues(item interface{}, tag string) (values url.Values)
- func URLKey(prefix, u string) string
- func UnixTimestampTrim(ts int64, sec int64) int64
- func ValidationErrorToText(e validator.FieldError) string
- func VarianceFloat64(fs []float64) (float64, error)
- func YiWanString(num float64) string
- type ErrCode
- func (c *ErrCode) AppendError(errs ...error) *ErrCode
- func (c *ErrCode) AppendMsg(msg string) *ErrCode
- func (c *ErrCode) Code() interface{}
- func (c *ErrCode) Decode() (interface{}, string, []error)
- func (c *ErrCode) Error() string
- func (c *ErrCode) Errs() []error
- func (c *ErrCode) Msg() string
- func (c *ErrCode) SetMsg(msg string) *ErrCode
- type GinStructValidator
- type Hashids
- type JSONTime
- type Pagination
Constants ¶
This section is empty.
Variables ¶
var ( // ErrGoCacheKeyNotFound go-cache get key 不存在 ErrGoCacheKeyNotFound = errors.New("cache key not found") // ErrGoCacheSetResultFailed go-cache get 转换为结果对象失败 ErrGoCacheSetResultFailed = errors.New("cache set result failed") )
var ChinaHolidays = map[string]map[string]bool{ "2021": ChinaHolidays2021, "2022": ChinaHolidays2022, }
ChinaHolidays 中国法定节假日
var ChinaHolidays2021 = map[string]bool{ "2021-01-01": true, "2021-01-02": true, "2021-01-03": true, "2021-02-11": true, "2021-02-12": true, "2021-02-13": true, "2021-02-14": true, "2021-02-15": true, "2021-02-16": true, "2021-02-17": true, "2021-04-03": true, "2021-04-04": true, "2021-04-05": true, "2021-05-03": true, "2021-05-04": true, "2021-05-05": true, "2021-06-12": true, "2021-06-13": true, "2021-06-14": true, "2021-09-19": true, "2021-09-20": true, "2021-09-21": true, "2021-10-01": true, "2021-10-02": true, "2021-10-03": true, "2021-10-04": true, "2021-10-05": true, "2021-10-06": true, "2021-10-07": true, }
ChinaHolidays2021 2021年中国法定节假日
var ChinaHolidays2022 = map[string]bool{ "2022-01-01": true, "2022-01-02": true, "2022-01-03": true, "2022-01-31": true, "2022-02-01": true, "2022-02-02": true, "2022-02-03": true, "2022-02-04": true, "2022-02-05": true, "2022-02-06": true, "2022-04-03": true, "2022-04-04": true, "2022-04-05": true, "2022-04-30": true, "2022-05-01": true, "2022-05-02": true, "2022-05-03": true, "2022-05-04": true, "2022-06-03": true, "2022-06-04": true, "2022-06-05": true, "2022-09-10": true, "2022-09-11": true, "2022-09-12": true, "2022-10-01": true, "2022-10-02": true, "2022-10-03": true, "2022-10-04": true, "2022-10-05": true, "2022-10-06": true, "2022-10-07": true, "2022-12-30": true, "2022-12-31": true, }
ChinaHolidays2022 2022年中国法定节假日
var ChinaHolidays2023 = map[string]bool{ "2022-01-01": true, "2023-01-22": true, "2023-01-23": true, "2023-01-24": true, "2023-01-25": true, "2023-01-26": true, "2023-01-27": true, "2023-01-28": true, "2023-04-03": true, "2023-04-04": true, "2023-04-05": true, "2023-04-29": true, "2023-04-30": true, "2023-05-01": true, "2023-06-22": true, "2023-06-23": true, "2023-06-24": true, "2023-09-29": true, "2023-09-30": true, "2023-10-01": true, "2023-10-02": true, "2023-10-03": true, "2023-10-04": true, "2023-10-05": true, "2023-10-06": true, }
ChinaHolidays2023 2023年中国法定节假日
var (
JSONTimeFormat = "2006-01-02 15:04:05"
)
JSONTimeFormat 定义 JSONTime 的时间格式 该值可以被外部修改为指定的其他格式
var RedisClusterInstances sync.Map
RedisClusterInstances 按 which key 保存 redis cluster 客户端实例
var RedisInstances sync.Map
RedisInstances 按 which key 保存 redis 客户端实例
var RedisSentinelInstances sync.Map
RedisSentinelInstances 按 which key 保存 redis sentinel 客户端实例
var ValidatorTagName = "binding"
ValidatorTagName 结构体 validator 的 tag 名
Functions ¶
func AnonymousName ¶
AnonymousName 返回游客昵称
func ChunkFloat64Slice ¶
ChunkFloat64Slice float64 slice 按指定大小进行切块
func CloseRedisInstances ¶
func CloseRedisInstances()
CloseRedisInstances 关闭全部的 redis 连接并重置 RedisInstances
func GetGoCache ¶
GetGoCache 封装go-cache 的 Get 方法支持直接获取具体类型
func GetLatestTradingDay ¶
func GetLatestTradingDay() string
GetLatestTradingDay 返回最近一个交易日string类型日期:YYYY-mm-dd
func HTTPGET ¶
func HTTPGET(ctx context.Context, cli *http.Client, apiurl string, header map[string]string, rspPointer interface{}) error
HTTPGET 发送 http get 请求并将返回结果 json unmarshal 到 rspPointer
func HTTPGETRaw ¶
func HTTPGETRaw(ctx context.Context, cli *http.Client, apiurl string, header map[string]string) ([]byte, error)
HTTPGETRaw 发送 http get 请求
func HTTPPOST ¶
func HTTPPOST(ctx context.Context, cli *http.Client, req *http.Request, rspPointer interface{}) error
HTTPPOST 发送 http post 请求并将结果 json unmarshal 到 rspPointer
func HTTPPOSTRaw ¶
HTTPPOSTRaw 发送 http post 请求
func InitViper ¶
InitViper 根据配置文件路径和名称初始化 viper 并监听变化 configFile 配置文件 onConfigChangeRun 配置文件发生变化时的回调函数
func IntHashDecode ¶
IntHashDecode 返回hash值对应的int
func IntHashEncode ¶
IntHashEncode 返回int的hash值
func IsEqualStringSlice ¶
IsEqualStringSlice 判断两个 string slice 是否相同
func JaccardSimilarity ¶
func JaccardSimilarity(s1, s2 []interface{}) float64
JaccardSimilarity Jaccard similarity相似性系数 J(A, B) = |A ∩ B | / | A ∪ B | A,B分别代表符合某种条件的集合:两个集合交集的大小/两个集合并集的大小,交集=并集意味着2个集合完全重合。
func MapIntIntSortedKeys ¶
MapIntIntSortedKeys 返回map[int]int{}按value排序的keys
func MapStrIntSortedKeys ¶
MapStrIntSortedKeys 返回map[string]int{}按value排序的keys
func MidValueFloat64 ¶
MidValueFloat64 获取中位数
func NewHTTPGetURLWithQueryString ¶
func NewHTTPGetURLWithQueryString(ctx context.Context, apiurl string, params map[string]string) (string, error)
NewHTTPGetURLWithQueryString 创建带 querystring 的 http get 请求 url
func NewHTTPJSONReq ¶
NewHTTPJSONReq 根据参数创建 json 请求
func NewHTTPMultipartReq ¶
func NewHTTPMultipartReq(ctx context.Context, apiurl string, reqData map[string]string) (*http.Request, error)
NewHTTPMultipartReq 根据参数创建 form-data 请求
func NewRedisClient ¶
func NewRedisClient(opt *redis.Options) (*redis.Client, error)
NewRedisClient 返回 redis 的客户端连接对象
func NewRedisClusterClient ¶
func NewRedisClusterClient(opt *redis.ClusterOptions) (*redis.ClusterClient, error)
NewRedisClusterClient 返回 redis cluster 的连接对象
func NewRedisFailoverClient ¶
func NewRedisFailoverClient(opt *redis.FailoverOptions) (*redis.Client, error)
NewRedisFailoverClient 返回带 sentinel 的 redis 连接对象
func RedisClient ¶
RedisClient 根据 viper 配置返回 redis 客户端
func RedisClusterClient ¶
RedisClusterClient 根据 viper 配置返回 redis cluster 实例
func RedisSentinelClient ¶
RedisSentinelClient 根据 viper 配置返回 redis 客户端
func RemoveAllWhitespace ¶
RemoveAllWhitespace 删除字符串中所有的空白符
func RemoveDuplicateWhitespace ¶
RemoveDuplicateWhitespace 删除字符串中重复的空白字符为单个空白字符 trim: 是否去掉首位空白
func RemoveStringSliceItemByIndex ¶
RemoveStringSliceItemByIndex 根据下标删除 string slice 中的元素
func RequestHTTPHandler ¶
func RequestHTTPHandler(app http.Handler, method, path string, body []byte, header map[string]string) (*httptest.ResponseRecorder, error)
RequestHTTPHandler 根据参数请求传入的 http.Handler 对应的 path 接口,用于接口测试 返回 ResponseRecorder: https://golang.org/pkg/net/http/httptest/#ResponseRecorder
func RequestHTTPHandlerFunc ¶
func RequestHTTPHandlerFunc(f http.HandlerFunc, method string, body []byte, header map[string]string) ([]byte, error)
RequestHTTPHandlerFunc 根据参数请求传入的 http.HandlerFunc 返回请求处理结果 body ,用于接口测试
func ReverseFloat64Slice ¶
func ReverseFloat64Slice(numbers []float64)
ReverseFloat64Slice 直接反转 float64 列表,无返回值
func ReversedFloat64Slice ¶
ReversedFloat64Slice 反转 float64 列表,有返回值
func SetRedisInstances ¶
SetRedisInstances 设置 redis 对象到 RedisInstances 中
func StdDeviationFloat64 ¶
StdDeviationFloat64 求标准差
func StrSimilarity ¶
StrSimilarity 提供不同的算法检测文本相似度
func StructTagList ¶
StructTagList 获取结构体 tag 列表
func StructToMap ¶
StructToMap 结构体转 Map
func StructToURLValues ¶
StructToURLValues 将结构体指针对象转换为 url.Values , key 为 json tag , value 为结构体字段值,没有 json tag 则使用字段名称
func UnixTimestampTrim ¶
UnixTimestampTrim 将 Unix 时间戳(秒)以指定秒数进行规整
func ValidationErrorToText ¶
func ValidationErrorToText(e validator.FieldError) string
ValidationErrorToText error msg for human
Types ¶
type ErrCode ¶
type ErrCode struct {
// contains filtered or unexported fields
}
ErrCode 错误码结构体
func NewErrCode ¶
NewErrCode 创建错误码,code 可以是任意类型
func (*ErrCode) AppendError ¶
AppendError 添加 err 到 errs 中
type GinStructValidator ¶
type GinStructValidator struct {
// contains filtered or unexported fields
}
GinStructValidator 自定义参数 binding 验证错误信息输出格式
func (*GinStructValidator) Engine ¶
func (v *GinStructValidator) Engine() interface{}
Engine returns the underlying validator engine which powers the default Validator instance. This is useful if you want to register custom validations or struct level validations. See validator GoDoc for more info - https://godoc.org/gopkg.in/go-playground/validator.v8
func (*GinStructValidator) ValidateStruct ¶
func (v *GinStructValidator) ValidateStruct(obj interface{}) error
ValidateStruct receives any kind of type, but only performed struct or pointer to struct type.
type Hashids ¶
type Hashids struct { HashID *hashids.HashID HashIDData *hashids.HashIDData // contains filtered or unexported fields }
Hashids 封装hashids方法
func MustNewHashids ¶
MustNewHashids 创建Hashids对象 salt可以使用用户创建记录时的用户唯一身份标识+当前时间戳的字符串作为值 minLength指定转换后的最小长度,随着数字ID的增大长度可能会变长
func NewHashids ¶
NewHashids 创建Hashids对象 salt可以使用用户创建记录时的用户唯一身份标识+当前时间戳的字符串作为值 minLength指定转换后的最小长度,随着数字ID的增大长度可能会变长
type JSONTime ¶
JSONTime 用于在 json 中自定义时间格式 json marshal 一个带有 time.Time 字段类型的结构体时,时间格式固定为 RFC3339 格式 将 time.Time 类型替换为 JSONTime 类型,可设置时间格式为 JSONTimeFormat 中定义的格式
func (JSONTime) MarshalJSON ¶
MarshalJSON 使用 JSONTimeFormat 覆盖 time 包中实现的 json.Marshaler 接口
type Pagination ¶
type Pagination struct { // 当前页面数据开始下标 StartIndex int `json:"start_index"` // 当前页面数据结束下标 EndIndex int `json:"end_index"` // 数据总数 TotalCount int `json:"total_count"` // 分页总数 PagesCount int `json:"pages_count"` // 当前页码 PageNum int `json:"page_num"` // 当前 offset PageOffset int `json:"page_offset"` // 上一页页码 PrevPageNum int `json:"prev_page_num"` // 下一页页码 NextPageNum int `json:"next_page_num"` // 分页大小 PageSize int `json:"page_size"` // 是否有上一页 HasPrev bool `json:"has_prev"` // 是否有下一页 HasNext bool `json:"has_next"` }
Pagination Paginate return it 异常数据时分页总数为 0 ,当前页码、上下页码均不判断逻辑,只管数值增减
func PaginateByOffsetLimit ¶
func PaginateByOffsetLimit(totalCount, offset, limit int) Pagination
PaginateByOffsetLimit 按 offset,limit 计算分页信息
func PaginateByPageNumSize ¶
func PaginateByPageNumSize(totalCount, pageNum, pageSize int) Pagination
PaginateByPageNumSize 按 pagenum,pagesize 计算分页信息 参数必须全部大于 0