gdk

package module
v0.0.0-...-110d06e Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2024 License: MIT Imports: 20 Imported by: 0

README

GDK(Golang Development Kit)

GitHub issues GitHub forks GitHub stars GitHub license Twitter

gdk

Getting Started

A collection of libraries to speed your Go development.

Installation

go get -v github.com/hollson/gdk

Examples

Documentation

Index

Examples

Constants

View Source
const (
	NumberSymbol = "0123456789"
	LetterSymbol = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	PassSymbol   = "!@#$%^&*()[]{}+-*/_=."
)
View Source
const (
	DefaultDateLayout = "2006-01-02"
	DefaultTimeLayout = "2006-01-02 15:04:05"
)
View Source
const BLANK = ""

Variables

View Source
var (
	ErrNotFound      = errors.New("not found")             // 未找到资源
	ErrParam         = errors.New("param error")           // 参数错误
	ErrAuth          = errors.New("auth error")            // 鉴权失败
	ErrIllegalUser   = errors.New("illegal user")          // 非法用户(跨账号操作等)
	ErrCSRFFail      = errors.New("CSRF invalid")          // 跨站请求失败
	ErrForbidden     = errors.New("forbidden")             // 无权操作
	ErrNetwork       = errors.New("network error")         // 网络错误
	ErrRepeatRequest = errors.New("repeat request")        // 重复请求(非幂等)
	ErrOutdatedVer   = errors.New("outdated version")      // 版本过期/不兼容
	ErrFileData      = errors.New("file data error")       // 文件格式/编码错误
	ErrFileSize      = errors.New("file size error")       // 文件尺寸错误
	ErrUploadFailed  = errors.New("upload failed")         // 文件上传失败
	ErrGateway       = errors.New("gateway error")         // 网关错误
	ErrServer        = errors.New("server error")          // 服务错误
	ErrServerTimeout = errors.New("server timeout")        // 服务处理超时
	ErrInMaintenance = errors.New("in maintenance")        // 系统维护中
	ErrDataOperation = errors.New("data operation failed") // 数据(库)处理错误
)
View Source
var (
	ErrUnsupportedInputType = errors.New("unsupported input type")
	ErrInvalidFormatRFC3339 = errors.New("must comply with RFC3339")
)
View Source
var ERR_BYTES_INVALILD = errors.New("BytesToFloat64 bytes invalid")

ERR_BYTES_INVALILD

View Source
var ERR_NEED_NUMERIC = errors.New("ToInt64 need numeric")

ERR_NEED_NUMERIC

View Source
var Logger *log.Logger

Functions

func Byte8

func Byte8(s []byte) []byte

Byte8 将给定的切片转换为[8]byte类型

说明: 使用copy(to,from)函数自由填充目标切片或数组,如:
       n:=copy(arr,slice) 或
       n:=copy(slice,arr)
Example
fmt.Println(Byte8([]byte{'a', 'b', 'c'}))
fmt.Println(Byte8([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9}))

// out:
// [97 98 99 0 0 0 0 0]
// [1 2 3 4 5 6 7 8]
Output:

func Bytes2I

func Bytes2I(b [8]byte) uint64

Bytes2I byte数组转换为int

func Bytes2IAuto

func Bytes2IAuto(b []byte) uint64

Bytes2IAuto byte数组转换为int

func BytesToFloat64

func BytesToFloat64(bytes []byte) (data float64, err error)

BytesToFloat64 convert bytes to float64

func CharCount

func CharCount(str string) int

CharCount 统计字符个数

与javascript中的string.length一致
Example
str := "Hello, 世界"
fmt.Println("bytes =", len(str))
fmt.Println("runes =", CharCount(str))
Output:


bytes = 13
runes = 9

func Contain

func Contain(tar interface{}, container interface{}) (bool, error)

目标元素tar是否包含在container集合中,container必须是切片类型

如:Contain(1,[]int{1,2,3})
   Contain(u,[]User{u1,u2,u3})
   Contain(&u,[]*User{&u1,&u2,&u3})
   Contain(1.0, []interface{}{1.0,"a",'b'})

func ContainByte

func ContainByte(tar byte, container ...byte) bool

目标元素tar是否包含在container集合中

func ContainFloat32

func ContainFloat32(tar float32, container ...float32) bool

目标元素tar是否包含在container集合中

func ContainFloat64

func ContainFloat64(tar float64, container ...float64) bool

目标元素tar是否包含在container集合中

func ContainInt

func ContainInt(tar int, container ...int) bool

目标元素tar是否包含在container集合中

func ContainInt32

func ContainInt32(tar int32, container ...int32) bool

目标元素tar是否包含在container集合中

func ContainInt64

func ContainInt64(tar int64, container ...int64) bool

目标元素tar是否包含在container集合中

func ContainMust

func ContainMust(tar interface{}, container interface{}) bool

同Contain,但需手动处理panic

func ContainString

func ContainString(tar string, container ...string) bool

目标元素tar是否包含在container集合中

func Convert2AnyTypeSlice

func Convert2AnyTypeSlice(slice interface{}) ([]interface{}, error)

Convert2AnyTypeSlice 将对象切片转换为接口切片

如: AnyTypeSlice([]int{1,2,3}) => []interface{}{1,2,3}

func Create

func Create(name string) (*os.File, error)

Create create one file

func Dir

func Dir(fp string) string

Dir get filepath dir name

func DirsUnder

func DirsUnder(dirPath string) ([]string, error)

DirsUnder list dirs under dirPath

func DistinctBytes

func DistinctBytes(tar byte, container ...byte) bool

目标元素tar是否包含在container集合中

func DistinctFloat32s

func DistinctFloat32s(tar float32, container ...float32) bool

目标元素tar是否包含在container集合中

func DistinctFloat64s

func DistinctFloat64s(tar float64, container ...float64) bool

目标元素tar是否包含在container集合中

func DistinctInt32s

func DistinctInt32s(tar int32, container ...int32) bool

目标元素tar是否包含在container集合中

func DistinctInt64s

func DistinctInt64s(tar int64, container ...int64) bool

目标元素tar是否包含在container集合中

func DistinctInts

func DistinctInts(tar int, container ...int) bool

目标元素tar是否包含在container集合中

func DistinctStrings

func DistinctStrings(tar string, container ...string) bool

目标元素tar是否包含在container集合中

func EnsureDirRW

func EnsureDirRW(dataDir string) error

EnsureDirRW ensure the datadir and make sure it's rw-able

func Ext

func Ext(fp string) string

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.

func FileEmpty

func FileEmpty(name string) bool

func FileExists

func FileExists(filename string) bool

func FileMTime

func FileMTime(fp string) (int64, error)

FileMTime get file modified time

func FileSize

func FileSize(fp string) (int64, error)

FileSize get file size as how many bytes

func FilesUnder

func FilesUnder(dirPath string) ([]string, error)

FilesUnder list files under dirPath

func FindProjectAbs

func FindProjectAbs() (string, error)

FindProjectAbs find absolute path that have go.mod in parent folder.

func Float64Precision

func Float64Precision(f float64, precision int, round bool) float64

Float64Precision float指定精度; round为true时, 表示支持四舍五入

func Float64ToBytes

func Float64ToBytes(input float64) []byte

Float64ToBytes convert float64 to bytes; []uint8

func Float64ToStr

func Float64ToStr(num float64, precision int) string

Float64ToStr convert float64 to string 支持指定精度

func GetRandomOne

func GetRandomOne(arr interface{}) interface{}

GetRandomOne get random element from an array/slice

func HasAny

func HasAny(src string, sub ...string) bool

HasAny raw中是否包含sub...中的任意子串

如: HasSub("datetime","date") => true
   HasSub("datetime","time") => true

func I2Bytes

func I2Bytes(v uint64) []byte

I2Bytes int转换为byte数组

func InsureDir

func InsureDir(fp string) error

InsureDir mkdir if not exist

func Is400

func Is400(str string) bool

Is400 是否匹配400电话

func IsChineseCharacter

func IsChineseCharacter(str string) bool

IsChineseCharacter 是否全是中文

func IsEmail

func IsEmail(str string) bool

IsEmail 是否匹配邮箱格式

func IsExist

func IsExist(fp string) bool

IsExist checks whether a file or directory exists It returns false when the file or directory does not exist.

func IsFile

func IsFile(fp string) bool

IsFile checks whether the path is a file, it returns false when it's a directory or does not exist.

func IsFloat

func IsFloat(str string) bool

IsFloat 整数或者小数

func IsHMS

func IsHMS(str string) bool

IsHMS 是否匹配日期格式

hh:mm:ss

func IsHMS_APM

func IsHMS_APM(str string) bool

IsHMS_APM 是否匹配日期格式(AP)

hh:mm:ss xx

func IsIP

func IsIP(str string) bool

IsIP 是否匹配IP格式

func IsNumber

func IsNumber(str string) bool

IsNumber 是否是数字

func IsPhone

func IsPhone(str string) bool

IsPhone 是否匹配手机号格式

func IsSlice

func IsSlice(o interface{}) (val reflect.Value, ok bool)

判断参数o是否为某个类型切片

如: IsSlice([]int{1,2,3}) => true

func IsSpecialSymbols

func IsSpecialSymbols(str string) bool

IsSpecialSymbols 是否以特殊符号开头

!@#$%^&*()_+-={}|[]\:";'<>?,./ 等

func IsTel

func IsTel(str string) bool

IsTel 是否匹配电话格式

func IsYMD

func IsYMD(str string) bool

IsYMD 是否匹配年份格式

(?!0000)  闰年:2016-02-29

func IsYMDHMS

func IsYMDHMS(str string) bool

IsYMDHMS 是否匹配日期时间格式

YYYY-MM-DD
(?!0000)  闰年:2016-02-29

func JoinByte

func JoinByte(arr []byte, splitter ...string) string

JoinByte 拼接切片

splitter:拼接符(默认为逗号)

func JoinInt

func JoinInt(arr []int, splitter ...string) string

JoinInt 将切片拼接成以splitter(默认逗号)分割等字符串

func JoinInt32

func JoinInt32(arr []int32, splitter ...string) string

将切片拼接成以splitter(默认逗号)分割等字符串

func JoinInt64

func JoinInt64(arr []int64, splitter ...string) string

func Json

func Json(o interface{}) string

Json 将对象转换为Json字符串

func JsonPretty

func JsonPretty(o interface{}) string

JsonPretty 将对象转换为美化的Json字符串

func Logf

func Logf(s string, args ...interface{})

func MapToStruct

func MapToStruct(obj map[string]interface{}, data interface{}) (interface{}, error)

MapToStruct map obj to struct data

func MatchAny

func MatchAny(src string, tars ...string) bool

MatchAny 判断src是否与tar中的任意元素匹配

func MatchString

func MatchString(pattern, input string) (bool, error)

MatchString returns true if current string match the pattern, false otherwise.

func Name

func Name(fp string) string

Name get filepath base name

func OpenFile

func OpenFile(filename string) (*os.File, error)

func ParseDate

func ParseDate(s string) time.Time

ParseDate 日前转换 (推荐使用 time.ParseInLocation)

将"2006-01-02"格式的字符串转换为时间. 参数错误时返回 1970-01-01(08:00:00GMT).

func ParseTime

func ParseTime(s string) time.Time

ParseTime 时间转换 (推荐使用 time.ParseInLocation)

将"2006-01-02 15:04:05"格式的字符串转换为时间. 参数错误时返回 1970-01-01(08:00:00GMT).

func Pascal

func Pascal(title string) string

Pascal 转换为帕斯卡命名

如: userName => UserName
   user_name => UserName

func RFC3339

func RFC3339(value interface{}) error

RFC3339 validates input is compliance with RFC3339

func RandInt

func RandInt(n int) int

RandInt 生成n以内的随机数

func RandInt64

func RandInt64(n int64) int64

RandInt64 生成n以内的随机数

func RandIntX deprecated

func RandIntX(n int) int

Deprecated: 推荐使用 RandInt

func RandNumStr

func RandNumStr(n int) string

RandNumStr 随机数字串,n为生成长度

func RandPassword

func RandPassword(n int) string

RandPassword 随机密码串(包含数字、大小写字母和特殊符号),n为生成长度

func RandScopeInt

func RandScopeInt(m, n int) int

RandScopeInt 生成m到n以内的随机数,左闭右开区间[m,n)

func RandSequence

func RandSequence(n int) string

RandSequence 带有时间序列的随机数字串,即14位时间字符+N个随机字符, 如:20060102150405+99999

func RandString

func RandString(n int) string

RandString 随机字符串(包含数字和大小写字母),n为生成长度

func RangeStringsFunc

func RangeStringsFunc(arr []string, f func(string) string)

RangeStringsFunc 遍历处理集合成员

func RangeToTitle

func RangeToTitle(arr []string)

RangeToTitle 遍历并将集合元素转换为Title格式

func ReadFile

func ReadFile(path string) string

func RealPath

func RealPath(fp string) (string, error)

RealPath get absolute filepath, based on built executable file

func Register

func Register(pattern string) (*regexp.Regexp, error)

Register creates a new regex from pattern it has not been created at least once yet.

func Remove

func Remove(name string) error

Remove remove one file

func Rename

func Rename(src string, target string) error

Rename rename file name

func ReplaceAllString

func ReplaceAllString(pattern, input, repl string) (string, error)

ReplaceAllString returns a copy of input, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first sub-match.

func ReverseBytes

func ReverseBytes(arr ...int)

倒序翻转(byte), 如:[9,5,2,7] => [7,2,5,9]

func ReverseFloat32s

func ReverseFloat32s(arr ...int)

倒序翻转(float32), 如:[9,5,2,7] => [7,2,5,9]

func ReverseFloat64s

func ReverseFloat64s(arr ...int)

倒序翻转(float64), 如:[9,5,2,7] => [7,2,5,9]

func ReverseInt32s

func ReverseInt32s(arr ...int)

倒序翻转(int32), 如:[9,5,2,7] => [7,2,5,9]

func ReverseInt64s

func ReverseInt64s(arr ...int)

倒序翻转(int64), 如:[9,5,2,7] => [7,2,5,9]

func ReverseInts

func ReverseInts(arr ...int)

倒序翻转(int),如:[9,5,2,7] => [7,2,5,9]

func ReverseStrings

func ReverseStrings(arr ...int)

倒序翻转(string), 如:["a","r","e"] => ["e","r","a"]

func SQLInInt

func SQLInInt(items ...int) (inSql string)

将切片拼接成「sql in」语句

如:{1,3,5,7,9} ==> "1,3,5,7,9"

func SQLInInt32

func SQLInInt32(items ...int32) (inSql string)

将切片拼接成「sql in」语句

如:{1,3,5,7,9} ==> "1,3,5,7,9"

func SQLInInt64

func SQLInInt64(items ...int64) (inSql string)

将切片拼接成「sql in」语句

如:{1,3,5,7,9} ==> "1,3,5,7,9"

func SQLInString

func SQLInString(items ...string) (inSql string)

将切片拼接成「sql in」语句

如:{"aa","bb","cc"} ==> "'1','3','5','7','9'"

func SearchFile

func SearchFile(filename string, paths ...string) (fullPath string, err error)

Search a file in the give paths. this is often used in search config file in /etc ~/

func SearchFileWithAffix

func SearchFileWithAffix(dirPath, prefix, suffix string) (fullPath string, exist bool)

func SelfDir

func SelfDir() string

SelfDir get compiled executable file directory

func SelfPath

func SelfPath() string

SelfPath gets compiled executable file absolute path

func StrToFloat64

func StrToFloat64(str string, precision int) float64

StrToFloat64 convert string to float64, supported the given precision

func StrToFloat64Round

func StrToFloat64Round(str string, precision int, round bool) float64

StrToFloat64Round convert string to float64, supported the given precision and round

func StringsRemove

func StringsRemove(ss []string, s string) []string

StringsRemove a value form a string slice

func StringsToInts

func StringsToInts(ss []string) (ints []int, err error)

StringsToInts string slice to int slice

func StringsToSlice

func StringsToSlice(strings []string) []interface{}

StringsToSlice convert []string to []interface{}

func StructToMap

func StructToMap(obj interface{}) map[string]interface{}

StructToMap struct convert to map

func Time1970 deprecated

func Time1970() time.Time

Deprecated: 推荐使用 time.Unix(0, 0)

1970年1月1日(08:00:00GMT)

func ToBool

func ToBool(b string) bool

ToBool 将字符串转换为bool类型,参数错误时返回false

1,t,T,TRUE, true, True  => true
0,f,F,FALSE,false,False => false

func ToInt

func ToInt(n string) (ret int)

将字符串转换为int64,转换失败时返回0

func ToInt64

func ToInt64(num string) int64

将字符串转换为int64,转换失败时返回0

func TrimSpace

func TrimSpace(str string) string

TrimSpace 修剪所有换行和空格,如:压缩整段格式化的SQL

func TrimStrings

func TrimStrings(ss []string, cutSet ...string) (ns []string)

TrimStrings trim string slice item.

Usage:

// output: [a, b, c]
ss = arrutil.TrimStrings([]string{",a", "b.", ",.c,"}, ",.")

Types

type JsonTime

type JsonTime time.Time

JsonTime 自定义Json成员类型

func (JsonTime) MarshalJSON

func (p JsonTime) MarshalJSON() ([]byte, error)

func (JsonTime) String

func (p JsonTime) String() string

func (JsonTime) UnmarshalJSON

func (p JsonTime) UnmarshalJSON(b []byte) error

type Loggerx

type Loggerx interface {
	Trace(requestID string, fields map[string]interface{}, message string)
	Debug(requestID string, fields map[string]interface{}, message string)
	Info(requestID string, fields map[string]interface{}, message string)

	Warn(requestID string, err error, fields map[string]interface{}, message string)
	Error(requestID string, err error, fields map[string]interface{}, message string)
	Fatal(requestID string, err error, fields map[string]interface{}, message string)
}

type Once

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

Once is an object that will perform exactly one action until Reset is called. See http://golang.org/pkg/sync/#Once

func (*Once) Do

func (o *Once) Do(f func())

Do simulates sync.Once.Do by executing the specified function only once, until Reset is called. See http://golang.org/pkg/sync/#Once

func (*Once) Reset

func (o *Once) Reset()

Reset indicates that the next call to Do should actually be called once again.

Directories

Path Synopsis
Package bitset implements bitsets, a mapping between non-negative integers and boolean values.
Package bitset implements bitsets, a mapping between non-negative integers and boolean values.
Package color 精简快捷的彩色字体工具包(Linux版本)
Package color 精简快捷的彩色字体工具包(Linux版本)
Package money 货币单位/换算
Package money 货币单位/换算
pkg
srcimporter
Package srcimporter implements importing directly from source files rather than installed packages.
Package srcimporter implements importing directly from source files rather than installed packages.
Package rat:实验鼠
Package rat:实验鼠
Package zero 类型缺省值
Package zero 类型缺省值

Jump to

Keyboard shortcuts

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