goutils

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2021 License: MIT Imports: 38 Imported by: 2

README

goutils

Golang 通用类函数工具包

功能概览

数据库相关
Redis 相关
文件相关
单元测试相关
IP 相关
时间相关
slice 相关
string 相关
配置相关
URL 相关
Struct 相关
HTTP 请求相关
时间相关
统计
其他分类

Documentation

Overview

Package goutils 是一个将开发中常用的通用类函数封装统一存放在这里以便复用的函数工具包

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrGoCacheKeyNotFound go-cache get key 不存在
	ErrGoCacheKeyNotFound = errors.New("cache key not found")
	// ErrGoCacheSetResultFailed go-cache get 转换为结果对象失败
	ErrGoCacheSetResultFailed = errors.New("cache set result failed")
)
View Source
var GormInstances sync.Map

GormInstances 以 sync.Map 保存 gorm db 相关信息 key 为小写的数据库驱动名称, value 为实例名为 key , 具体的 db 对象为 value 的 sync.Map 形如: {"mysql": {"localhost": db}, "postgres": {"localhost": db}}

View Source
var (
	JSONTimeFormat = "2006-01-02 15:04:05"
)

JSONTimeFormat 定义 JSONTime 的时间格式 该值可以被外部修改为指定的其他格式

View Source
var RedisClusterInstances sync.Map

RedisClusterInstances 按 which key 保存 redis cluster 客户端实例

View Source
var RedisInstances sync.Map

RedisInstances 按 which key 保存 redis 客户端实例

View Source
var RedisSentinelInstances sync.Map

RedisSentinelInstances 按 which key 保存 redis sentinel 客户端实例

View Source
var SqlxInstances sync.Map

SqlxInstances 以 sync.Map 保存 sqlx db 相关信息 key 为小写的数据库驱动名称, value 为实例名为 key , 具体的 db 对象为 value 的 sync.Map 形如: {"mysql": {"localhost": db}, "postgres": {"localhost": db}}

View Source
var ValidatorTagName = "binding"

ValidatorTagName 结构体 validator 的 tag 名

Functions

func AvgFloat64

func AvgFloat64(f []float64) (float64, error)

AvgFloat64 平均值

func ChunkFloat64Slice

func ChunkFloat64Slice(data []float64, chunkSize int) [][]float64

ChunkFloat64Slice float64 slice 按指定大小进行切块

func CloseGormInstances

func CloseGormInstances()

CloseGormInstances 关闭全部的 Gorm 连接并重置 GormInstances

func CloseRedisInstances

func CloseRedisInstances()

CloseRedisInstances 关闭全部的 redis 连接并重置 RedisInstances

func CloseSqlxInstances

func CloseSqlxInstances()

CloseSqlxInstances 关闭全部的 Sqlx 连接并重置 SqlxInstances

func CopyFile

func CopyFile(sourceFile, destinationFile string) (err error)

CopyFile 复制文件

func GetGoCache

func GetGoCache(c *cache.Cache, key string, resultPointer interface{}) error

GetGoCache 封装go-cache 的 Get 方法支持直接获取具体类型

func GetLocalIP

func GetLocalIP() (string, error)

GetLocalIP 获取当前 IP

func GormMySQL

func GormMySQL(which string) (*gorm.DB, error)

GormMySQL 根据 viper 配置中的实例名称返回 gorm 连接 mysql 的实例

func GormPostgres

func GormPostgres(which string) (*gorm.DB, error)

GormPostgres 根据 viper 配置中的实例名称返回 pg 实例

func GormSQLite3

func GormSQLite3(which string) (*gorm.DB, error)

GormSQLite3 根据 viper 配置中的实例名称返回 sqlite3 实例

func GormSqlserver

func GormSqlserver(which string) (*gorm.DB, error)

GormSqlserver 根据 viper 配置中的实例名称返回 sqlserver 实例

func HTTPGET

func HTTPGET(ctx context.Context, cli *http.Client, apiurl string, rspPointer interface{}) error

HTTPGET 发送 http get 请求并将返回结果 json unmarshal 到 rspPointer

func HTTPGETRaw

func HTTPGETRaw(ctx context.Context, cli *http.Client, apiurl 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

func HTTPPOSTRaw(ctx context.Context, cli *http.Client, req *http.Request) ([]byte, error)

HTTPPOSTRaw 发送 http post 请求

func InitViper

func InitViper(configPath, configName, configType string, onConfigChangeRun func(fsnotify.Event)) error

InitViper 根据配置文件路径和名称初始化 viper 并监听变化 configPath 配置文件路径 configName 配置文件名(不带格式后缀) configType 配置文件格式后缀 onConfigChangeRun 配置文件发生变化时的回调函数

func IsEqualStringSlice

func IsEqualStringSlice(s1, s2 []string) bool

IsEqualStringSlice 判断两个 string slice 是否相同

func IsInitedViper

func IsInitedViper() bool

IsInitedViper 返回 viper 是否已初始化

func IsIntInSlice

func IsIntInSlice(i int, s []int) bool

IsIntInSlice 判断字符串是否在给定的字符串列表中

func IsStrInSlice

func IsStrInSlice(i string, s []string) bool

IsStrInSlice 判断字符串是否在给定的字符串列表中

func JaccardSimilarity

func JaccardSimilarity(s1, s2 []interface{}) float64

JaccardSimilarity Jaccard similarity相似性系数 J(A, B) = |A ∩ B | / | A ∪ B | A,B分别代表符合某种条件的集合:两个集合交集的大小/两个集合并集的大小,交集=并集意味着2个集合完全重合。

func LikeFieldEscape

func LikeFieldEscape(value string) string

LikeFieldEscape 转义 SQL 的 like 模糊查询时字段值为通配符的值

func MidValueFloat64

func MidValueFloat64(values []float64) (float64, error)

MidValueFloat64 获取中位数

func NewGormMySQL

func NewGormMySQL(conf DBConfig) (*gorm.DB, error)

NewGormMySQL 返回 gorm mysql 连接实例

func NewGormPostgres

func NewGormPostgres(conf DBConfig) (*gorm.DB, error)

NewGormPostgres 返回 gorm postgresql 连接实例

func NewGormSQLite3

func NewGormSQLite3(conf DBConfig) (*gorm.DB, error)

NewGormSQLite3 返回 gorm sqlite3 连接实例

func NewGormSqlserver

func NewGormSqlserver(conf DBConfig) (*gorm.DB, error)

NewGormSqlserver 返回 gorm sqlserver 连接实例

func NewHTTPGetURLWithQueryString

func NewHTTPGetURLWithQueryString(ctx context.Context, apiurl string, params map[string]string) (string, error)

NewHTTPGetURLWithQueryString 创建带 querystring 的 http get 请求 url

func NewHTTPJSONReq

func NewHTTPJSONReq(ctx context.Context, apiurl string, reqData interface{}) (*http.Request, error)

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 NewSqlxMsSQL

func NewSqlxMsSQL(conf DBConfig) (*sqlx.DB, error)

NewSqlxMsSQL 返回 sqlx sqlserver 连接实例

func NewSqlxMySQL

func NewSqlxMySQL(conf DBConfig) (*sqlx.DB, error)

NewSqlxMySQL 返回 sqlx mysql 连接实例

func NewSqlxPostgres

func NewSqlxPostgres(conf DBConfig) (*sqlx.DB, error)

NewSqlxPostgres 返回 sqlx postgresql 连接实例

func NewSqlxSQLite3

func NewSqlxSQLite3(conf DBConfig) (*sqlx.DB, error)

NewSqlxSQLite3 返回 sqlx sqlite3 连接实例

func RedisClient

func RedisClient(which string) (*redis.Client, error)

RedisClient 根据 viper 配置返回 redis 客户端

func RedisClusterClient

func RedisClusterClient(which string) (*redis.ClusterClient, error)

RedisClusterClient 根据 viper 配置返回 redis cluster 实例

func RedisSentinelClient

func RedisSentinelClient(which string) (*redis.Client, error)

RedisSentinelClient 根据 viper 配置返回 redis 客户端

func RemoveAllWhitespace

func RemoveAllWhitespace(s string) string

RemoveAllWhitespace 删除字符串中所有的空白符

func RemoveDuplicateWhitespace

func RemoveDuplicateWhitespace(s string, trim bool) string

RemoveDuplicateWhitespace 删除字符串中重复的空白字符为单个空白字符 trim: 是否去掉首位空白

func RemoveStringSliceItemByIndex

func RemoveStringSliceItemByIndex(slice []string, index int) []string

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 ReverseString

func ReverseString(s string) string

ReverseString 翻转字符串

func ReversedFloat64Slice

func ReversedFloat64Slice(numbers []float64) []float64

ReversedFloat64Slice 反转 float64 列表,有返回值

func SetGormInstances

func SetGormInstances(driverName, which string, db *gorm.DB) error

SetGormInstances 设置 gorm db 对象到 GormInstances 中

func SetRedisInstances

func SetRedisInstances(which string, rdb *redis.Client) error

SetRedisInstances 设置 redis 对象到 RedisInstances 中

func SplitStringFields

func SplitStringFields(s string) []string

SplitStringFields 将传入字符串分割为slice

func SqlxMsSQL

func SqlxMsSQL(which string) (*sqlx.DB, error)

SqlxMsSQL 根据 viper 中配置的实例名称返回 sqlserver 实例

func SqlxMySQL

func SqlxMySQL(which string) (*sqlx.DB, error)

SqlxMySQL 根据 viper 中配置的实例名称返回 sqlx 连接 mysql 的实例

func SqlxPostgres

func SqlxPostgres(which string) (*sqlx.DB, error)

SqlxPostgres 根据 viper 中配置的实例名称返回 pg 实例

func SqlxSQLite3

func SqlxSQLite3(which string) (*sqlx.DB, error)

SqlxSQLite3 根据 viper 中配置的实例名称返回 sqlite3 实例

func StdDeviationFloat64

func StdDeviationFloat64(fs []float64) (float64, error)

StdDeviationFloat64 求标准差

func StrSimilarity

func StrSimilarity(s1, s2 string, algorithm string) float64

StrSimilarity 提供不同的算法检测文本相似度

func StrToTime

func StrToTime(layout, value string, loc ...*time.Location) (time.Time, error)

StrToTime 字符串时间转 time 对象

func StructTagList

func StructTagList(item interface{}, tag string) []string

StructTagList 获取结构体 tag 列表

func StructToMap

func StructToMap(item interface{}, tag string) map[string]interface{}

StructToMap 结构体转 Map

func StructToURLValues

func StructToURLValues(item interface{}, tag string) (values url.Values)

StructToURLValues 将结构体指针对象转换为 url.Values , key 为 json tag , value 为结构体字段值,没有 json tag 则使用字段名称

func URLKey

func URLKey(prefix, u string) string

URLKey 根据 url 生成 key ,默认使用 url escape ,长度超过 200 则使用 sha1 结果

func UnixTimestampTrim

func UnixTimestampTrim(ts int64, sec int64) int64

UnixTimestampTrim 将 Unix 时间戳(秒)以指定秒数进行规整

func ValidationErrorToText

func ValidationErrorToText(e validator.FieldError) string

ValidationErrorToText error msg for human

func VarianceFloat64

func VarianceFloat64(fs []float64) (float64, error)

VarianceFloat64 求方差

func YiWanString

func YiWanString(num float64) string

YiWanString 将数字转换为 亿/万

Types

type DBConfig

type DBConfig struct {
	// DriverName 数据库 driver 类型
	DriverName string
	// Host 数据库 IP 地址
	Host string
	// Port 数据库端口
	Port int
	// Username 数据库用户名
	Username string
	// Password 数据库密码
	Password string
	// DBName 数据库名称
	DBName string
	// LogMode 是否开启打印日志模式
	LogMode bool
	// MaxIdleConns 设置空闲连接池中的最大连接数
	MaxIdleConns int
	// MaxOpenConns 设置与数据库的最大打开连接数
	MaxOpenConns int
	// ConnMaxLifeMinutes 设置可重用连接的最长时间(分钟)
	ConnMaxLifeMinutes int
	// ConnTimeout 连接超时时间(秒)
	ConnTimeout int
	// ReadTimeout 读超时时间(秒)
	ReadTimeout int
	// WriteTimeout 写超时时间(秒)
	WriteTimeout int
	// DisableSSL 是否关闭 ssl 模式
	DisableSSL bool
	// gorm config
	GormConfig *gorm.Config
}

DBConfig 数据库配置

func (DBConfig) MySQLDSN

func (conf DBConfig) MySQLDSN() (string, error)

MySQLDSN 返回 Mysql dsn 字符串

func (DBConfig) PostgresDSN

func (conf DBConfig) PostgresDSN() (string, error)

PostgresDSN 返回 postgres dns 字符串

func (DBConfig) SQLite3DSN

func (conf DBConfig) SQLite3DSN() (string, error)

SQLite3DSN 返回 sqlite3 文件名

func (DBConfig) SqlserverDSN

func (conf DBConfig) SqlserverDSN() (string, error)

SqlserverDSN 返回 sqlserver dns 字符串

type ErrCode

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

ErrCode 错误码结构体

func NewErrCode

func NewErrCode(code interface{}, msg string, errs ...error) *ErrCode

NewErrCode 创建错误码,code 可以是任意类型

func (*ErrCode) AppendError

func (c *ErrCode) AppendError(errs ...error) *ErrCode

AppendError 添加 err 到 errs 中

func (*ErrCode) AppendMsg

func (c *ErrCode) AppendMsg(msg string) *ErrCode

AppendMsg 追加 msg 字段

func (*ErrCode) Code

func (c *ErrCode) Code() interface{}

Code 返回 code

func (*ErrCode) Decode

func (c *ErrCode) Decode() (interface{}, string, []error)

Decode 返回结构体里面的字段

func (*ErrCode) Error

func (c *ErrCode) Error() string

Error 拼接所有 err 信息并返回

func (*ErrCode) Errs

func (c *ErrCode) Errs() []error

Errs 返回 error 列表

func (*ErrCode) Msg

func (c *ErrCode) Msg() string

Msg 返回 msg 描述

func (*ErrCode) SetMsg

func (c *ErrCode) SetMsg(msg string) *ErrCode

SetMsg 更新 msg 字段

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 GormBaseModel

type GormBaseModel struct {
	ID        string   `gorm:"primary_key,column:id" json:"id"         example:"-"` // 字符串类型的 Hash 主键 ID
	CreatedAt JSONTime `gorm:"column:created_at"     json:"created_at" example:"-"` // 创建时间
	UpdatedAt JSONTime `gorm:"column:updated_at"     json:"updated_at" example:"-"` // 更新时间
}

GormBaseModel 基础 model 定义

type Hashids

type Hashids struct {
	HashID     *hashids.HashID
	HashIDData *hashids.HashIDData
	// contains filtered or unexported fields
}

Hashids 封装hashids方法

func NewHashids

func NewHashids(salt string, minLength int, prefix string) (*Hashids, error)

NewHashids 创建Hashids对象 salt可以使用用户创建记录时的用户唯一身份标识+当前时间戳的字符串作为值 minLength指定转换后的最小长度,随着数字ID的增大长度可能会变长

func (*Hashids) Decode

func (h *Hashids) Decode(hashID string) (int64, error)

Decode 将生成的随机字符串ID转为为原始的数字类型ID

func (*Hashids) Encode

func (h *Hashids) Encode(int64ID int64) (string, error)

Encode 将数字类型的ID转换为指定长度的随机字符串ID int64ID为需要转换的数字id,在没有自增主键ID时,可以采用当前用户已存在的记录数+1作为数字id,保证该数字在该用户下唯一

type JSONTime

type JSONTime struct {
	time.Time
}

JSONTime 用于在 json 中自定义时间格式 json marshal 一个带有 time.Time 字段类型的结构体时,时间格式固定为 RFC3339 格式 将 time.Time 类型替换为 JSONTime 类型,可设置时间格式为 JSONTimeFormat 中定义的格式

func NewJSONTime

func NewJSONTime(t time.Time) JSONTime

NewJSONTime 创建 JSONTime 对象

func (JSONTime) MarshalJSON

func (t JSONTime) MarshalJSON() ([]byte, error)

MarshalJSON 使用 JSONTimeFormat 覆盖 time 包中实现的 json.Marshaler 接口

func (*JSONTime) Scan

func (t *JSONTime) Scan(v interface{}) error

Scan 在 gorm 中只重写 MarshalJSON 是不够的,只写这个方法会在写数据库的时候会提示 delete_at 字段不存在,需要加上 database/sql 的 Value 和 Scan 方法

func (JSONTime) String

func (t JSONTime) String() string

String 实现 String 方法 用于 print

func (JSONTime) Value

func (t JSONTime) Value() (driver.Value, error)

Value 在 gorm 中只重写 MarshalJSON 是不够的,只写这个方法会在写数据库的时候会提示 delete_at 字段不存在,需要加上 database/sql 的 Value 和 Scan 方法

type Pagination

type Pagination struct {
	// 当前页面数据开始下标
	StartIndex int
	// 当前页面数据结束下标
	EndIndex int
	// 数据总数
	TotalCount int `json:"total_count"`
	// 分页总数
	PagesCount int `json:"pages_count"`
	// 当前页码
	PageNum int `json:"page_num"`
	// 上一页页码
	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

Jump to

Keyboard shortcuts

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