util

package
v0.0.0-...-95b0639 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2024 License: MIT Imports: 42 Imported by: 0

Documentation

Index

Constants

View Source
const R = 6367000 // 地球平均半径(单位为千米)

Variables

View Source
var (
	// Epoch is set to the twitter snowflake epoch of Nov 04 2010 01:42:54 UTC in milliseconds
	// You may customize this to set a different epoch for your application.
	Epoch int64 = 1288834974657

	// NodeBits holds the number of bits to use for Node
	// Remember, you have a total 22 bits to share between Node/Step
	NodeBits uint8 = 10

	// StepBits holds the number of bits to use for Step
	// Remember, you have a total 22 bits to share between Node/Step
	StepBits uint8 = 12
)
View Source
var CacheMemory *cache.Cache
View Source
var ErrInvalidBase32 = errors.New("invalid base32")

ErrInvalidBase32 is returned by ParseBase32 when given an invalid []byte

View Source
var ErrInvalidBase58 = errors.New("invalid base58")

ErrInvalidBase58 is returned by ParseBase58 when given an invalid []byte

Functions

func ArrDel

func ArrDel[T StrNumber](s []T, elem T) []T

func ArrWalk

func ArrWalk[T any, S any](s []T, walkFunc func(index int, item T) S) []S

func CRC32BigFile

func CRC32BigFile(f *os.File) string

func CRC32Encode

func CRC32Encode(input []byte) string

func CaptchaGenerate

func CaptchaGenerate() (string, string, error)

func CaptchaGenerate1

func CaptchaGenerate1() (string, string, error)

func CaptchaVerify

func CaptchaVerify(id, VerifyValue string) bool

func CheckImageExt

func CheckImageExt(fileName string, exts []string) bool

CheckImageExt check image file ext

func CheckImageSize

func CheckImageSize(fileHeader *multipart.FileHeader, maxSize int) bool

CheckImageSize check image size

func CheckPath

func CheckPath(src string) error

CheckPath check and make path dir

func ConvertExcelDateToFormatDay

func ConvertExcelDateToFormatDay(excelDaysString string) string

ConvertExcelDateToFormatDay excel日期字段格式化 yyyy-mm-dd

func ConvertToStringMap

func ConvertToStringMap(data interface{}) map[string]string

ConvertToStringMap 将一个数据结构转换为字符串键值对

func ConvertToStringMapRecursively

func ConvertToStringMapRecursively(prefix string, data interface{}, result map[string]string)

ConvertToStringMapRecursively 递归地将数据结构转换为字符串键值对

func Copy

func Copy(src, dst string) error

func CopyDir

func CopyDir(src, dst string) error

func DeepCopyMap

func DeepCopyMap(src map[int64]interface{}) map[int64]interface{}

func DownloadFile

func DownloadFile(c *gin.Context, path, name string) error

func FindToken

func FindToken(c *gin.Context, cookieKey string) string

func FindUser

func FindUser(c *gin.Context) *model.User

func FindUserId

func FindUserId(c *gin.Context) int64

func GenerateRandomString

func GenerateRandomString(length int) string

func GenerateToken

func GenerateToken(username, accessToken string, expiredAt int64, userType int, jwtSecret []byte) (string, error)

GenerateToken generate tokens used for auth

func GeoDistance

func GeoDistance(lat1, lon1, lat2, lon2 float64) float64

func GetArrayMaybeValue

func GetArrayMaybeValue[T string](arr []T, index int) T

func GetDaysInMonth

func GetDaysInMonth(year int, month time.Month) int

GetDaysInMonth 返回指定年份和月份的天数

func GetDefaultCacheMemory

func GetDefaultCacheMemory() *cache.Cache

func GetImageBase64Content

func GetImageBase64Content(fileName, suffix string) (string, error)

GetImageBase64Content 获取 图片的 base64 内容 xxx.jpg ===> xxx.base64

func GetImageName

func GetImageName(name string) string

GetImageName get image name

func GetRandomWithAll

func GetRandomWithAll(min, max int) int64

GetRandomWithAll 获取指定范围的随机整数,包含上下限

func GetTimeConditionWhere

func GetTimeConditionWhere(req *request.TimeConditionRule) map[string]map[string]interface{}

func GetWSSessionKey

func GetWSSessionKey(header http.Header) string

func GetWSSessionKeyByKey

func GetWSSessionKeyByKey(platFormKey int) string

func GetWeek

func GetWeek(year int, month time.Month, day int) (latestDay time.Weekday)

func GetWeekendInYear

func GetWeekendInYear(timestamp int64) int

func HttpFile

func HttpFile(c *gin.Context, filepath string, filename string)

func HttpReturn

func HttpReturn(c *gin.Context, httpCode int, errCode code.ErrCode, err error, data interface{})

func HttpReturn500

func HttpReturn500(c *gin.Context, errCode code.ErrCode, err error, data interface{})

func HttpReturnOK

func HttpReturnOK(c *gin.Context, errCode code.ErrCode, err error, data interface{})

func HttpReturnValidateFailed

func HttpReturnValidateFailed(c *gin.Context, err error, data interface{})

func Image2Base64

func Image2Base64(fileName string) (string, error)

func InArrStrNum

func InArrStrNum[T StrNumber](s []T, needle T) bool

func InArrStruct

func InArrStruct[T any](s []T, needle T, eqFunc func(i, needle T) bool) bool

func InRange

func InRange(points []Point, point *Point) bool

func IsNight

func IsNight(t time.Time) bool

func IsStringEmpty

func IsStringEmpty(str string) bool

func IsWeekend

func IsWeekend(t time.Time) bool

func MD5BigFile

func MD5BigFile(f *os.File) string

func MD5BytesEncode

func MD5BytesEncode(value []byte) string

func MD5Encode

func MD5Encode(value string) string

func MergeStructs

func MergeStructs(dst interface{}, srcs ...interface{}) error

MergeStructs 将多个源结构体的字段值合并到目标结构体中。 dst 是目标结构体的指针,srcs 是源结构体的切片。 函数会尝试将源结构体中每个字段的值复制到目标结构体对应的字段中。 如果目标结构体中有对应的字段且可设置,则进行值的复制。 参数:

dst - 目标结构体的指针,其值将被源结构体的值更新。
srcs - 源结构体的切片,其值将被复制到目标结构体。

返回值:

error - 如果操作中出现错误,则返回错误;否则返回nil。

func NewCacheMemory

func NewCacheMemory(defaultExpiration, cleanupInterval time.Duration) *cache.Cache

func OverrideGinValidator

func OverrideGinValidator()

func ParseStrTimeCondition2Int

func ParseStrTimeCondition2Int(timeCondition *TimeCondition, timeField string, where map[string]interface{}) map[string]interface{}

func PasswordHash

func PasswordHash(pwd []byte) string

func PasswordVerify

func PasswordVerify(hashedPwd string, plainPwd string) bool

func RequestPlatform

func RequestPlatform(header http.Header) int

func RequestPlatformByXPlatformFrom

func RequestPlatformByXPlatformFrom(XPlatformFrom string) int

func SmsCaptchaGenerate

func SmsCaptchaGenerate(phone string) string

func SmsCaptchaVerify

func SmsCaptchaVerify(phone string, code string) (bool, error)

func StrPad

func StrPad(str string, placeholder string, overallLen int) string

func Translate

func Translate(err error) string

Translate 测验并返回测验错误信息

func TrimHandlerName

func TrimHandlerName(handlerName string) string

func UUID

func UUID(nodeId int64) string

func UnZip

func UnZip()

func UniqueArrStrNum

func UniqueArrStrNum[T StrNumber](s []T) []T

func Upload

func Upload(c *gin.Context, uploadFile *multipart.FileHeader, dir string) (string, error)

func UploadFile

func UploadFile(f io.Reader, storagePath, filename string) (string, string, error)

func UploadFileByMultipartFileHeader

func UploadFileByMultipartFileHeader(f *multipart.FileHeader, storagePath string) (string, string, error)

func UploadPath

func UploadPath(dir, filename string) string

func WGS84ToCGCS2000

func WGS84ToCGCS2000(lon, lat float64) []float64

func Zip

func Zip(src, dst string) error

Types

type Area

type Area struct {
	Points []Point //多边形坐标 顺时针方向
}

func NewArea

func NewArea(points []Point) *Area

func (*Area) InRange

func (a *Area) InRange(point *Point) bool

type Claims

type Claims struct {
	Username    string           `json:"username,omitempty"`
	AccessToken string           `json:"access_token,omitempty"`
	ExpiresAt   *jwt.NumericDate `json:"expires_at,omitempty"`
	IssuedAt    *jwt.NumericDate `json:"iat,omitempty"`

	Audience  []string         `json:"aud,omitempty"`
	Id        string           `json:"jti,omitempty"`
	Issuer    string           `json:"iss,omitempty"`
	NotBefore *jwt.NumericDate `json:"nbf,omitempty"`
	Subject   string           `json:"sub,omitempty"`
}

func ParseToken

func ParseToken(token string, jwtSecret []byte) (*Claims, error)

ParseToken parsing token

func (Claims) GetAudience

func (c Claims) GetAudience() (jwt.ClaimStrings, error)

func (Claims) GetExpirationTime

func (c Claims) GetExpirationTime() (*jwt.NumericDate, error)

func (Claims) GetIssuedAt

func (c Claims) GetIssuedAt() (*jwt.NumericDate, error)

func (Claims) GetIssuer

func (c Claims) GetIssuer() (string, error)

func (Claims) GetNotBefore

func (c Claims) GetNotBefore() (*jwt.NumericDate, error)

func (Claims) GetSubject

func (c Claims) GetSubject() (string, error)

type Config

type Config struct {
	Host string `json:"host" yaml:"host" mapstructure:"host"`
	Port int    `json:"port" yaml:"port" mapstructure:"port"`
	User string `json:"user" yaml:"user" mapstructure:"user"`
	Pass string `json:"pass" yaml:"pass" mapstructure:"pass"`
}

type Email

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

func NewEmail

func NewEmail(conf *Config, l log.Log) *Email

func (*Email) Mail

func (e *Email) Mail(sendTos []string, m *gomail.Message) error

type HttpResponse

type HttpResponse struct {
	Code code.ErrCode `json:"code"`
	Msg  string       `json:"msg"`
	Data interface{}  `json:"data"`
}

type ID

type ID int64

An ID is a custom type used for a snowflake ID. This is used so we can attach methods onto the ID.

func ParseBase2

func ParseBase2(id string) (ID, error)

ParseBase2 converts a Base2 string into a snowflake ID

func ParseBase32

func ParseBase32(b []byte) (ID, error)

ParseBase32 parses a base32 []byte into a snowflake ID NOTE: There are many different base32 implementations so becareful when doing any interoperation.

func ParseBase36

func ParseBase36(id string) (ID, error)

ParseBase36 converts a Base36 string into a snowflake ID

func ParseBase58

func ParseBase58(b []byte) (ID, error)

ParseBase58 parses a base58 []byte into a snowflake ID

func ParseBase64

func ParseBase64(id string) (ID, error)

ParseBase64 converts a base64 string into a snowflake ID

func ParseBytes

func ParseBytes(id []byte) (ID, error)

ParseBytes converts a byte slice into a snowflake ID

func ParseInt64

func ParseInt64(id int64) ID

ParseInt64 converts an int64 into a snowflake ID

func ParseIntBytes

func ParseIntBytes(id [8]byte) ID

ParseIntBytes converts an array of bytes encoded as big endian integer as a snowflake ID

func ParseString

func ParseString(id string) (ID, error)

ParseString converts a string into a snowflake ID

func (ID) Base2

func (f ID) Base2() string

Base2 returns a string base2 of the snowflake ID

func (ID) Base32

func (f ID) Base32() string

Base32 uses the z-base-32 character set but encodes and decodes similar to base58, allowing it to create an even smaller result string. NOTE: There are many different base32 implementations so becareful when doing any interoperation.

func (ID) Base36

func (f ID) Base36() string

Base36 returns a base36 string of the snowflake ID

func (ID) Base58

func (f ID) Base58() string

Base58 returns a base58 string of the snowflake ID

func (ID) Base64

func (f ID) Base64() string

Base64 returns a base64 string of the snowflake ID

func (ID) Bytes

func (f ID) Bytes() []byte

Bytes returns a byte slice of the snowflake ID

func (ID) Int64

func (f ID) Int64() int64

Int64 returns an int64 of the snowflake ID

func (ID) IntBytes

func (f ID) IntBytes() [8]byte

IntBytes returns an array of bytes of the snowflake ID, encoded as a big endian integer.

func (ID) MarshalJSON

func (f ID) MarshalJSON() ([]byte, error)

MarshalJSON returns a json byte array string of the snowflake ID.

func (ID) Node

func (f ID) Node() int64

Node returns an int64 of the snowflake ID node number DEPRECATED: the below function will be removed in a future release.

func (ID) Step

func (f ID) Step() int64

Step returns an int64 of the snowflake step (or sequence) number DEPRECATED: the below function will be removed in a future release.

func (ID) String

func (f ID) String() string

String returns a string of the snowflake ID

func (ID) Time

func (f ID) Time() int64

Time returns an int64 unix timestamp in milliseconds of the snowflake ID time DEPRECATED: the below function will be removed in a future release.

func (*ID) UnmarshalJSON

func (f *ID) UnmarshalJSON(b []byte) error

UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.

type JSONSyntaxError

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

A JSONSyntaxError is returned from UnmarshalJSON if an invalid ID is provided.

func (JSONSyntaxError) Error

func (j JSONSyntaxError) Error() string

type Mail

type Mail interface {
	Mail(sendTos []string, m *gomail.Message) error
}

type Node

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

A Node struct holds the basic information needed for a snowflake generator node

func NewNode

func NewNode(node int64) (*Node, error)

NewNode returns a new snowflake node that can be used to generate snowflake IDs

func (*Node) Generate

func (n *Node) Generate() ID

Generate creates and returns a unique snowflake ID To help guarantee uniqueness - Make sure your system is keeping accurate system time - Make sure you never have multiple nodes running with the same node ID

type Number

type Number interface {
	uint | uint8 | uint16 | uint32 | uint64 | int | int8 | int16 | int32 | int64 | float32 | float64
}

type Point

type Point struct {
	Lng float64 `json:"lng"` //经度(180°W-180°E) -180 - 0 - 180
	Lat float64 `json:"lat"` //纬度(90°S-90°N)-90 -0 -90
}

func NewPoint

func NewPoint(lat, lng float64) *Point

type SmsCode

type SmsCode struct {
	Code string     `json:"code"`
	T    *time.Time `json:"t"`
}

type StrNumber

type StrNumber interface {
	uint | uint8 | uint16 | uint32 | uint64 | int | int8 | int16 | int32 | int64 | float32 | float64 | string
}

type TimeCondition

type TimeCondition struct {
	StartTime int64 `json:"start_time"`
	EndTime   int64 `json:"end_time"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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