Documentation ¶
Overview ¶
Package utils add some context function
Package shortid enables the generation of short, unique, non-sequential and by default URL friendly Ids. The package is heavily inspired by the node.js https://github.com/dylang/shortid library.
Id Length ¶
The standard Id length is 9 symbols when generated at a rate of 1 Id per millisecond, occasionally it reaches 11 (at the rate of a few thousand Ids per millisecond) and very-very rarely it can go beyond that during continuous generation at full throttle on high-performant hardware. A test generating 500k Ids at full throttle on conventional hardware generated the following Ids at the head and the tail (length > 9 is expected for this test):
-NDveu-9Q iNove6iQ9J NVDve6-9Q VVDvc6i99J NVovc6-QQy VVoveui9QC ... tFmGc6iQQs KpTvcui99k KFTGcuiQ9p KFmGeu-Q9O tFTvcu-QQt tpTveu-99u
Life span ¶
The package guarantees the generation of unique Ids with zero collisions for 34 years (1/1/2016-1/1/2050) using the same worker Id within a single (although concurrent) application if application restarts take longer than 1 millisecond. The package supports up to 32 works, all providing unique sequences.
Implementation details ¶
Although heavily inspired by the node.js shortid library this is not a simple Go port. In addition it
- is safe to concurrency;
- does not require any yearly version/epoch resets;
- provides stable Id size over a long period at the rate of 1ms;
- guarantees no collisions (due to guaranteed fixed size of Ids between milliseconds and because multiple requests within the same ms lead to longer Ids with the prefix unique to the ms);
- supports 32 over 16 workers.
The algorithm uses less randomness than the original node.js implementation, which permits to extend the life span as well as reduce and guarantee the length. In general terms, each Id has the following 3 pieces of information encoded: the millisecond (first 8 symbols), the worker Id (9th symbol), running concurrent counter within the same millisecond, only if required, over all remaining symbols. The element of randomness per symbol is 1/2 for the worker and the millisecond and 0 for the counter. Here 0 means no randomness, i.e. every value is encoded using a 64-base alphabet; 1/2 means one of two matching symbols of the supplied alphabet, 1/4 one of four matching symbols. The original algorithm of the node.js module uses 1/4 throughout.
All methods accepting the parameters that govern the randomness are exported and can be used to directly implement an algorithm with e.g. more randomness, but with longer Ids and shorter life spans.
Index ¶
- Constants
- func ByteToJson[T any](b []byte) (T, error)
- func CalcAge(birthdayStr string) (int32, error)
- func CalcAgeWithoutErr(birthdayStr string) int32
- func CheckFileExist(src string) bool
- func CheckFileExt(fileName string, allowExts []string) bool
- func CheckFileSize(f multipart.File, fileSize int) bool
- func CheckNotExist(src string) bool
- func CheckPathExist(path string) (bool, error)
- func CheckPermission(src string) bool
- func CheckSign() gin.HandlerFunc
- func CopyFile(src, dst string) (err error)
- func CreateSign(param []byte) string
- func CreateToken(userNo string) string
- func Decode(input []byte, output interface{}) error
- func DeepCopy(value interface{}) interface{}
- func DeleteFile(filepath string) error
- func Distance(poi1, poi2 *DistanceOption) float64
- func ExportExcel(name string, header []string, headerKV map[string]string, ...) (fileNamePath string, err error)
- func FindIndex(ids []int, x int) int
- func FloatRetain(f float64, point int32) float64
- func FormatLocation2String(longitude, latitude float64) string
- func Generate() (string, error)
- func GetCurrentTimestampInt() int64
- func GetCurrentTimestampString() string
- func GetDate() string
- func GetDateAndHour() string
- func GetDateAndSec() string
- func GetDateByTime(someTime int64) string
- func GetDateDetailString() string
- func GetDateOnly() string
- func GetDayTime() int64
- func GetExt(fileName string) string
- func GetFileFullName(name string) string
- func GetFileModifyTime(fileFullPath string) int64
- func GetFileName(fileFullPath string) string
- func GetFileSize(filename string) (int, error)
- func GetFilename(filePath string) string
- func GetFirstDateOfWeek(nowTime time.Time) time.Time
- func GetFullHourString(timeIn int64) (string, string)
- func GetHost(ctx *gin.Context) (host string)
- func GetHourByString(stringTime string) (error, time.Time)
- func GetHourString(timeIn int64) string
- func GetIntNotZeroOrDefault(i *int, dft int) int
- func GetIntOrDefault(i *int, dft int) int
- func GetLastDayString(timeIn int64) (string, string)
- func GetMaxDateTime() string
- func GetMessageId() string
- func GetMinDateTime() string
- func GetRandomInt(min, max int) int
- func GetSize(f multipart.File) (int, error)
- func In(s string, lst []string) bool
- func InArray(num int, slice []int) bool
- func Interface2String(inter interface{}, param ...int) string
- func Intersect(sliceA []int, sliceB []int) []int
- func IsAllWhiteSpace(s string) bool
- func IsNil(i interface{}) bool
- func IsNotExistMkDir(src string) error
- func Join(arr []int, split string) string
- func JoinStringArray(arr []string, sep string) string
- func MapToJson[T any](m map[string]interface{}) (T, error)
- func MkDir(src string) error
- func MustGenerate() string
- func MustOpen(fileName, filePath string) (*os.File, error)
- func Open(name string, flag int, perm os.FileMode) (*os.File, error)
- func PbJson2String(ctx context.Context, pbStruct any) string
- func ReadExcel(filename, sheetName string) (rows [][]string, err error)
- func ReadFile(file string) string
- func ReadJsonFile(filePath string) (result string)
- func SaveFile(filepath, content string) error
- func SaveJson(marshal []byte, jsonFile string) (err error)
- func SetDefault(sid *Shortid)
- func SetEmpty(s string) string
- func StrictStructCopy(src interface{}, dst interface{})
- func String2Float64(s string) float64
- func String2Float64WithDefaultError(s string) float64
- func String2Int32(s string) int32
- func String2Int64(s string) int64
- func StringToJson[T any](s string) (T, error)
- func StructCopyUseJson(src interface{}, dst interface{})
- func StructCopyUseReflect(dst interface{}, src interface{}) (err error)
- func StructToJSONKeyValueSorted(s interface{}) string
- func StructToKeyValueSorted(s any) string
- func StructToMap(st interface{}) map[string]interface{}
- func StructToMapUseJson(st interface{}) map[string]interface{}
- func StructToXMLKeyValueSorted(s interface{}, skipKeys []string) string
- func Subtract(sa []int, sb []int) []int
- func Time2Date(timeStr time.Time) string
- func Time2DateMonthOnly(timeStr time.Time) string
- func TimeCompare(timeBefore, timeAfter string) bool
- func ToInt(i interface{}) int
- func ToIntSlice(str string, separator string) (rst []int)
- func ToJsonByte(v any) ([]byte, error)
- func ToJsonSortedString(v any) (string, error)
- func ToJsonString(v any) (string, error)
- func VerifyCarLicenseFormat(license string) bool
- func VerifyIPFormat(ip string) bool
- func VerifyMobileFormat(mobileNum string) bool
- type Abc
- type Cmp
- type DistanceOption
- type Shortid
- func (sid *Shortid) Abc() Abc
- func (sid *Shortid) Epoch() time.Time
- func (sid *Shortid) Generate() (string, error)
- func (sid *Shortid) GenerateInternal(tm *time.Time, epoch time.Time) (string, error)
- func (sid *Shortid) MustGenerate() string
- func (sid *Shortid) String() string
- func (sid *Shortid) Worker() uint
- type SignPrams
- type Snowflake
- type TimeDetail
- type TokenInfo
Constants ¶
const DefaultABC = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
DefaultABC is the default URL-friendly alphabet.
const EarthRadius = 6371.0 // 地球半径(km)
const SIGNKEY = "5506eb75f447d18a2ff9cfdd7d9820fe"
const Version = 1.1
Version defined the library version.
Variables ¶
This section is empty.
Functions ¶
func ByteToJson ¶
func CalcAgeWithoutErr ¶ added in v1.8.0
CalcAgeWithoutErr Calculate birthday based on date, date format: yyyy-MM-DD, return without err
func CheckFileExt ¶
CheckFileExt check image file ext
func CheckFileSize ¶
CheckFileSize check image size
func CheckPermission ¶
CheckPermission check if the file has permission
func CheckSign ¶
func CheckSign() gin.HandlerFunc
func CopyFile ¶
CopyFile copies a file from src to dst. If src and dst files exist, and are the same, then return success. Otherise, attempt to create a hard link between the two files. If that fail, copy the file contents from src to dst.
func CreateSign ¶
func CreateToken ¶
func DeepCopy ¶
func DeepCopy(value interface{}) interface{}
DeepCopy Deprecated:未经过实际测试,可能存在无法预知的问题
func DeleteFile ¶
func Distance ¶
func Distance(poi1, poi2 *DistanceOption) float64
func ExportExcel ¶
func ExportExcel(name string, header []string, headerKV map[string]string, data []map[string]interface{}, filePath string) (fileNamePath string, err error)
ExportExcel 导出Excel表格 *
- @param name {string} 导出的表名
- @param header {[]string} 表头key,导出后显示的顺序
- @param headerKV {map[string]string} 表头、数据kv对照
- @param data {[]map[string]interface{}} 数据集合
- @param filePath {string} 文件保存路径,需要带"/"
- @return err {error} 异常
func FormatLocation2String ¶
func GetCurrentTimestampInt ¶ added in v1.4.0
func GetCurrentTimestampInt() int64
func GetCurrentTimestampString ¶ added in v1.4.0
func GetCurrentTimestampString() string
func GetDateAndHour ¶
func GetDateAndHour() string
func GetDateAndSec ¶
func GetDateAndSec() string
func GetDateByTime ¶
func GetDateDetailString ¶
func GetDateDetailString() string
func GetDateOnly ¶
func GetDateOnly() string
func GetDayTime ¶
func GetDayTime() int64
func GetFileFullName ¶
func GetFileModifyTime ¶
func GetFileName ¶
func GetFileSize ¶
func GetFilename ¶
func GetFirstDateOfWeek ¶
GetFirstDateOfWeek 计算本周周一的日期
func GetFullHourString ¶
func GetHourString ¶
func GetIntNotZeroOrDefault ¶
func GetIntOrDefault ¶
func GetLastDayString ¶
func GetMaxDateTime ¶ added in v1.9.0
func GetMaxDateTime() string
GetMaxDateTime Retrieve the maximum date formats for the current time's day
func GetMessageId ¶
func GetMessageId() string
func GetMinDateTime ¶ added in v1.9.0
func GetMinDateTime() string
GetMinDateTime Retrieve the minimum date formats for the current time's day
func Interface2String ¶
func IsNotExistMkDir ¶
IsNotExistMkDir create a directory if it does not exist
func JoinStringArray ¶ added in v1.3.0
JoinStringArray 将字符串数组,用指定分隔符连接
func MustGenerate ¶
func MustGenerate() string
MustGenerate acts just like Generate, but panics instead of returning errors.
func PbJson2String ¶ added in v1.7.0
PbJson2String Output pb parameters in the form of JSON strings
func ReadJsonFile ¶
func StrictStructCopy ¶
func StrictStructCopy(src interface{}, dst interface{})
StrictStructCopy 严格的struct拷贝 Deprecated:未经过实际测试,可能存在无法预知的问题
func String2Float64 ¶ added in v1.3.0
func String2Float64WithDefaultError ¶ added in v1.3.0
func String2Int32 ¶ added in v1.3.0
func String2Int64 ¶
func StringToJson ¶
func StructCopyUseJson ¶
func StructCopyUseJson(src interface{}, dst interface{})
StructCopyUseJson 利用json做中间值进行拷贝
func StructCopyUseReflect ¶
func StructCopyUseReflect(dst interface{}, src interface{}) (err error)
StructCopyUseReflect 利用反射进行拷贝 已知问题:对组合型结构体拷贝存在问题
func StructToJSONKeyValueSorted ¶ added in v1.4.0
func StructToJSONKeyValueSorted(s interface{}) string
StructToJSONKeyValueSorted
Concatenate the structure tag into a key=value format for parameters, and sort them in ASCII lexicographic order by parameter name
func StructToKeyValueSorted ¶ added in v1.4.0
StructToKeyValueSorted
Concatenate the structure into a key=value format for parameters, and sort them in ASCII lexicographic order by parameter name
func StructToMap ¶
func StructToMap(st interface{}) map[string]interface{}
StructToMap Deprecated:未经过实际测试,可能存在无法预知的问题
func StructToMapUseJson ¶
func StructToMapUseJson(st interface{}) map[string]interface{}
StructToMapUseJson 结构体转KV
func StructToXMLKeyValueSorted ¶ added in v1.4.0
StructToXMLKeyValueSorted
Concatenate the structure tag into a key=value format for parameters, and sort them in ASCII lexicographic order by parameter name
func Time2DateMonthOnly ¶
func TimeCompare ¶
func ToIntSlice ¶
func ToJsonByte ¶
func ToJsonSortedString ¶ added in v1.12.0
ToJsonSortedString Sort the structure into a JSON string in ascending order according to the first letter ASCII code
func ToJsonString ¶
func VerifyCarLicenseFormat ¶
func VerifyIPFormat ¶
func VerifyMobileFormat ¶
Types ¶
type Abc ¶
type Abc struct {
// contains filtered or unexported fields
}
Abc represents a shuffled alphabet used to generate the Ids and provides methods to encode data.
func MustNewAbc ¶
MustNewAbc acts just like NewAbc, but panics instead of returning errors.
func NewAbc ¶
NewAbc constructs a new instance of shuffled alphabet to be used for Id representation.
func (*Abc) Encode ¶
Encode encodes a given value into a slice of runes of length nsymbols. In case nsymbols==0, the length of the result is automatically computed from data. Even if fewer symbols is required to encode the data than nsymbols, all positions are used encoding 0 where required to guarantee uniqueness in case further data is added to the sequence. The value of digits [4,6] represents represents n in 2^n, which defines how much randomness flows into the algorithm: 4 -- every value can be represented by 4 symbols in the alphabet (permitting at most 16 values), 5 -- every value can be represented by 2 symbols in the alphabet (permitting at most 32 values), 6 -- every value is represented by exactly 1 symbol with no randomness (permitting 64 values).
func (*Abc) MustEncode ¶
MustEncode acts just like Encode, but panics instead of returning errors.
type DistanceOption ¶
type Shortid ¶
type Shortid struct {
// contains filtered or unexported fields
}
Shortid type represents a short Id generator working with a given alphabet.
func GetDefault ¶
func GetDefault() *Shortid
GetDefault retrieves the default short Id generator initialised with the default alphabet, worker=0 and seed=1. The default can be overwritten using SetDefault.
func New ¶
New constructs an instance of the short Id generator for the given worker number [0,31], alphabet (64 unique symbols) and seed value (to shuffle the alphabet). The worker number should be different for multiple or distributed processes generating Ids into the same data space. The seed, on contrary, should be identical.
func (*Shortid) Epoch ¶
Epoch returns the value of epoch used as the beginning of millisecond counting (normally 2016-01-01 00:00:00 local time)
func (*Shortid) GenerateInternal ¶
GenerateInternal should only be used for testing purposes.
func (*Shortid) MustGenerate ¶
MustGenerate acts just like Generate, but panics instead of returning errors.
type Snowflake ¶ added in v1.4.0
type Snowflake struct {
// contains filtered or unexported fields
}
func NewSnowflake ¶ added in v1.4.0
NewSnowflake Init Snow-Flake worker
type TimeDetail ¶
type TimeDetail struct { Year string `json:"year"` Month string `json:"month"` Date string `json:"date"` Hour string `json:"hour"` Minute string `json:"minute"` Second string `json:"second"` }
func GetTimeDetail ¶
func GetTimeDetail(someTime int64) (detail TimeDetail)
type TokenInfo ¶
type TokenInfo struct { Raw string // The original string of the token Sub string `json:"sub"` UserId string `json:"user_id"` CurrentTimeMillis string `json:"currentTimeMillis"` Exp int64 `json:"exp"` Iat int64 `json:"iat"` Jti string `json:"jti"` }
func GetOriginalsInfo ¶
func GetOriginalsInfo(claims interface{}) *TokenInfo
func ParseToken ¶
func ParseTokenWithoutVerify ¶
解析JWT,但不验证签名