goutils

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2020 License: MIT Imports: 30 Imported by: 46

Documentation

Overview

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

Index

Constants

This section is empty.

Variables

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}}

Functions

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 GetLocalIP

func GetLocalIP() (string, error)

GetLocalIP 获取当前 IP

func GinValidationErrorToText added in v1.0.1

func GinValidationErrorToText(e validator.FieldError) string

GinValidationErrorToText error msg for human

func GormMsSQL

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

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

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 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 LikeFieldEscape

func LikeFieldEscape(value string) string

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

func NewGormMsSQL

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

NewGormMsSQL 返回 gorm sqlserver 连接实例

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 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 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 ReverseString

func ReverseString(s string) string

ReverseString 翻转字符串

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 StructToURLValues

func StructToURLValues(i interface{}) (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 结果

Types

type DBConfig

type DBConfig struct {
	// DriverName 数据库名
	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
}

DBConfig 数据库配置

func (DBConfig) MsSQLDSN

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

MsSQLDSN 返回 mssql dns 字符串

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 文件名

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 added in v1.0.1

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 added in v1.0.1

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

GinStructValidator 自定义参数 binding 验证错误信息输出格式

func (*GinStructValidator) Engine added in v1.0.1

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 added in v1.0.1

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 {
	// 数据总数
	TotalCount int `json:"total_count"`
	// 分页总数
	PagesCount int `json:"pages_count"`
	// 当前页码
	PageNum int `json:"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