util

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2023 License: MIT Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	//TimeZone ...
	TimeZone = "Asia/Shanghai"
	//Custom ...
	Custom = "2006-01-02 15:04:05"
	//DateLayout ...
	DateLayout = "2006-01-02"
)
View Source
const (
	B = 1 << (10 * iota)
	KB
	MB
	GB
	TB
	PB
	EB
)

Byte unit helpers.

View Source
const (
	Alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
View Source
const PathUpload = "upload"

Variables

View Source
var (
	AppName    = "glib"
	CompileMod string
	Version    string
	BuildTime  string
	GoVersion  string
	GitBranch  string
	GitHash    string
)
View Source
var (
	ErrorFileIsNotImage = errors.New("文件类型错误")
	ErrorFileIsTooLarge = errors.New("文件不能超过2MB")
)
View Source
var ErrInvalidType = errors.New("invalid type")
View Source
var ErrPassword = errors.New("密码错误")
View Source
var RootDir = func() string {
	ec, _ := os.Executable()
	return filepath.Dir(ec)
}
View Source
var TimeNowFunc = time.Now

TimeNowFunc ...

View Source
var ValidatorInc = new(Validator).New()

Functions

func AddressCanListen

func AddressCanListen(addr string) bool

func AnyType

func AnyType[T any]() reflect.Type

func AnyValuePointer

func AnyValuePointer[T any](v T) *T

func BeanHasFieldCallback

func BeanHasFieldCallback(bean interface{}, fieldName string, calls ...func(v reflect.Value)) bool

BeanHasFieldCallback ... 判断是否存在字段 并回调

func CeilFloat64

func CeilFloat64(val float64, precision int) float64

CeilFloat64 按小数位截取float 最大值

func CheckPassword

func CheckPassword(p, c string) error

CheckPassword ...c cipher_password p plaintext

func CloseWriters

func CloseWriters()

func ConcurrentRun

func ConcurrentRun(fn func(), num int)

func Contains

func Contains[T comparable](a []T, x T) bool

func DecryptPassword

func DecryptPassword(p string) (s string, err error)

DecryptPassword ...

func EncryptPassword

func EncryptPassword(p string) string

EncryptPassword ...

func FloorFloat64

func FloorFloat64(val float64, precision int) float64

FloorFloat64 按小数位截取float 最小值

func FuncName

func FuncName(fn interface{}) string

FuncName ...

func FuncNameFull

func FuncNameFull(fn interface{}) string

func GJson added in v1.0.0

func GJson(data []byte) gjson.Result

func GenNanoid added in v1.0.0

func GenNanoid(n int) string

func GenNanoidNums added in v1.0.0

func GenNanoidNums(ns ...int) string

func GenUUID16

func GenUUID16(sep string, uuidVs ...uuid.UUID) string

func GenUUID16unix

func GenUUID16unix(sep string, uuidVs ...uuid.UUID) string

func GetLogWriter

func GetLogWriter(logName string) io.WriteCloser

func InjectPopulate

func InjectPopulate(values ...interface{})

InjectPopulate ...

func JSONDump

func JSONDump(val interface{}, args ...interface{}) string

JSONDump ...

func JSONEncodeDisableEscapeHTML added in v1.0.0

func JSONEncodeDisableEscapeHTML(val interface{}) (bytesResult []byte, err error)

func JSONExchange

func JSONExchange(dst interface{}, src interface{}) error

JSONExchange ...使用json copy对象

func JSONMarshalToBase64

func JSONMarshalToBase64(val interface{}) ([]byte, error)

JSONMarshalToBase64 ...

func JSONUnmarshalFromBase64

func JSONUnmarshalFromBase64(data []byte, val interface{}) error

JSONUnmarshalFromBase64 ...

func JsMarshal

func JsMarshal(val interface{}) (bts []byte)

JsMarshal ...

func JsMarshalHex

func JsMarshalHex(val interface{}) (dst []byte, err error)

func JsMarshalIndent

func JsMarshalIndent(val interface{}) (bts []byte)

JsMarshalIndent ...

func JsUnmarshalHex

func JsUnmarshalHex(data []byte, val interface{}) (err error)

func LoadAntSPool added in v1.0.0

func LoadAntSPool() *ants.Pool

func LoadSingle

func LoadSingle[T any](newFunc func() T) T

func LoadSingleInstance

func LoadSingleInstance[T any](key string, newFunc func() T) T

LoadSingleInstance load the single instance

func LocalUploadPath

func LocalUploadPath() string

func MD5

func MD5(s string) string

func Marshal

func Marshal(v interface{}) ([]byte, error)

func MarshalIndent

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

func MarshalToString

func MarshalToString(v interface{}, args ...interface{}) (string, error)

MarshalToString ...

func MergeBean added in v0.0.6

func MergeBean(target, source interface{}) error

MergeBean ...if source's field is not empty, then set target's field to source's field target and source must be pointer if source's field is empty, then target's field will not be changed

func MergeMap added in v0.0.6

func MergeMap(target, source Map)

func MustParsePreFloat64

func MustParsePreFloat64(value float64, pre int) float64

MustParsePreFloat64 按小数位截取float

func NewGroupError

func NewGroupError(group []error) error

func NewValue

func NewValue(bean interface{}) (val interface{})

NewValue ...

func ObjectTagInstances

func ObjectTagInstances(obj interface{}, tagName string) []interface{}

ObjectTagInstances ... *

  • @Description:根据标签获取字段实例集合
  • @param obj
  • @param tagName
  • @return []interface{}

func RandString

func RandString(n int) string

func ReflectIndirect

func ReflectIndirect(v interface{}) reflect.Value

ReflectIndirect ...

func ReflectValue

func ReflectValue(bean interface{}, fn func(v reflect.Value))

ReflectValue ...回调函数

func ReflectZeroFields

func ReflectZeroFields(v interface{}, fields []string)

ReflectZeroFields 将多个字段设置为零值

func RemoveUploadFile

func RemoveUploadFile(filePathName string)

func RetryDo

func RetryDo(fn func() error, intervalSecond int64) error

RetryDo 重试行为

func RetryDoTimes

func RetryDoTimes(times, intervalSecond int64, fn func() error) error

RetryDoTimes ...

func RoundFloat64

func RoundFloat64(val float64, precision int) float64

RoundFloat64 按小数位截取float 四舍五入

func SetInnerCrypto

func SetInnerCrypto(k string)

SetInnerCrypto ... must replace your own crypto

func SetJson added in v1.0.0

func SetJson(data []byte, path string, val interface{}) []byte

func SetTimeZone

func SetTimeZone() error

SetTimeZone ...Shanghai

func ShortUUID

func ShortUUID(uuidVs ...uuid.UUID) string

func SlicePointerValue

func SlicePointerValue(bean interface{}) reflect.Value

SlicePointerValue ...构建类型切片

func TextTemplateMustParse

func TextTemplateMustParse(text string, data interface{}) (result string)

TextTemplateMustParse ...

func Ticker

func Ticker(d time.Duration, fn func())

Ticker ...

func TimeExcWrap

func TimeExcWrap(fn func()) time.Duration

TimeExcWrap 包装执行时间

func TimeNow

func TimeNow() time.Time

TimeNow ...

func TodayDate

func TodayDate() string

TodayDate ...

func TrimByteSliceSpace added in v1.0.0

func TrimByteSliceSpace(data []byte) []byte

func TrimKey

func TrimKey(k string) string

func UUID16md5hex

func UUID16md5hex(uuidVs ...uuid.UUID) string

func UUIDString

func UUIDString(uuidVs ...uuid.UUID) string

UUIDString ...

func Unmarshal

func Unmarshal(data []byte, v interface{}) error

func UnmarshalFromString

func UnmarshalFromString(data string, v interface{}) error

UnmarshalFromString ...

func Upload

func Upload(r *http.Request) (filePathName string, err error)

func ValueIndirect

func ValueIndirect(val reflect.Value) reflect.Value

ValueIndirect ...值类型

func WaitSignal added in v1.0.0

func WaitSignal()

func WrapSignal added in v1.0.0

func WrapSignal(fn func())

Types

type CloseableChannel

type CloseableChannel[T any] struct {
	// contains filtered or unexported fields
}

func NewCloseable

func NewCloseable[T any](ch chan T) *CloseableChannel[T]

func (*CloseableChannel[T]) Channel

func (c *CloseableChannel[T]) Channel() <-chan T

Channel returns the channel of the CloseableChannel.

func (*CloseableChannel[T]) Close

func (c *CloseableChannel[T]) Close()

func (*CloseableChannel[T]) Dequeue

func (c *CloseableChannel[T]) Dequeue() (val T, ok bool)

Dequeue removes a value from the front of the queue

func (*CloseableChannel[T]) Enqueue

func (c *CloseableChannel[T]) Enqueue(value T)

Enqueue adds a value to the end of the queue

func (*CloseableChannel[T]) IsClosed

func (c *CloseableChannel[T]) IsClosed() bool

func (*CloseableChannel[T]) LockWrapFunc

func (c *CloseableChannel[T]) LockWrapFunc(fn func())

func (*CloseableChannel[T]) RLockWrapFunc

func (c *CloseableChannel[T]) RLockWrapFunc(fn func())

func (*CloseableChannel[T]) Send

func (c *CloseableChannel[T]) Send(val T)

func (*CloseableChannel[T]) SendWithDefaultTimeout

func (c *CloseableChannel[T]) SendWithDefaultTimeout(val T)

func (*CloseableChannel[T]) SendWithTimeout

func (c *CloseableChannel[T]) SendWithTimeout(val T, timeout time.Duration)

SendWithTimeout send val to the channel with timeout

type CloseableType

type CloseableType interface {
	IsClosed() bool
	Close()
	Send(val interface{})
	Channel() <-chan interface{}
}

type Cron

type Cron struct {
	*cron.Cron
}

func (*Cron) Constructor

func (c *Cron) Constructor()

type Crypto

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

Crypto ...

func NewCrypto

func NewCrypto(key string) *Crypto

NewCrypto ...

func (*Crypto) Decrypt

func (c *Crypto) Decrypt(ciphertext string) (string, error)

Decrypt ...

func (*Crypto) DecryptCBC

func (c *Crypto) DecryptCBC(ciphertext string) (string, error)

DecryptCBC ...

func (*Crypto) Encrypt

func (c *Crypto) Encrypt(val string) string

Encrypt ...

func (*Crypto) EncryptCBC

func (c *Crypto) EncryptCBC(val string) string

EncryptCBC ...

func (*Crypto) Key

func (c *Crypto) Key() string

Key ...

type Decoder

type Decoder = json.Decoder

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

type Encoder

type Encoder = json.Encoder

func NewEncoder

func NewEncoder(w io.Writer) *Encoder

type GQueue

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

func NewGQueue

func NewGQueue(opt GQueueOption) *GQueue

func (*GQueue) Enqueue

func (g *GQueue) Enqueue(task QueueTask)

func (*GQueue) Register

func (g *GQueue) Register(task string, handler GQueueHandler)

Register register task handler

func (*GQueue) StartServer added in v0.0.2

func (g *GQueue) StartServer()

StartServer ...

func (*GQueue) Wait added in v1.0.0

func (g *GQueue) Wait()

Wait ...

type GQueueHandler

type GQueueHandler func(task *QueueTask) (err error)

type GQueueOption

type GQueueOption struct {
	MaxWorkers int
	MaxRetry   int
	Logger     ItfLogger
	/**
	 * task groups
	 * key: group id
	 * value: the percentage of workers to be used for this group
	 */
	Groups map[int]int
}

type ItfLogger added in v0.0.2

type ItfLogger interface {
	Close() error
	SetOutput(writer io.Writer)
	Writer() io.Writer
	Print(i ...interface{})
	Printf(s string, i ...interface{})
	Println(i ...interface{})
	Fatal(i ...interface{})
	Fatalf(s string, i ...interface{})
	Fatalln(i ...interface{})
	Panic(i ...interface{})
	Panicf(s string, i ...interface{})
	Panicln(i ...interface{})
	Debugf(s string, i ...interface{})
	Infof(s string, i ...interface{})
	Warnf(s string, i ...interface{})
	Errorf(s string, i ...interface{})
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})
}

func ZapLogger

func ZapLogger(logName string, args ...string) ItfLogger

ZapLogger ...获取一个logger实例

type JSONTime

type JSONTime time.Time

JSONTime ...

func Must2JSONTimeAddr

func Must2JSONTimeAddr(in string) *JSONTime

Must2JSONTimeAddr maybe panic

func NewJSONTimeOfTime

func NewJSONTimeOfTime(t time.Time) *JSONTime

NewJSONTimeOfTime 时间转换为JSONTime

func Now

func Now() *JSONTime

Now 当前时间

func ToDatetime

func ToDatetime(in string) (JSONTime, error)

ToDatetime ...

func Today

func Today() *JSONTime

Today ...今日日期

func (*JSONTime) Add

func (p *JSONTime) Add(d time.Duration) *JSONTime

Add ...

func (*JSONTime) Convert2Time

func (p *JSONTime) Convert2Time() time.Time

Convert2Time ...

func (*JSONTime) Date

func (p *JSONTime) Date() *JSONTime

Date ...返回一个日期0点的时间

func (*JSONTime) FromDB

func (p *JSONTime) FromDB(data []byte) error

FromDB ...

func (*JSONTime) GobDecode

func (p *JSONTime) GobDecode(data []byte) error

GobDecode implements the gob.GobDecoder interface.

func (*JSONTime) GobEncode

func (p *JSONTime) GobEncode() ([]byte, error)

GobEncode implements the gob.GobEncoder interface.

func (*JSONTime) MarshalJSON

func (p *JSONTime) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*JSONTime) Scan

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

Scan the value of time.Time

func (*JSONTime) SetByTime

func (p *JSONTime) SetByTime(timeVal time.Time)

SetByTime ...

func (*JSONTime) String

func (p *JSONTime) String() string

String ...

func (*JSONTime) StringFormat

func (p *JSONTime) StringFormat(layout string) string

StringFormat 转换为固定格式字符串

func (*JSONTime) Time

func (p *JSONTime) Time() time.Time

Time ...

func (*JSONTime) ToDB

func (p *JSONTime) ToDB() (b []byte, err error)

ToDB ...

func (*JSONTime) UnmarshalJSON

func (p *JSONTime) UnmarshalJSON(data []byte) error

UnmarshalJSON ...

func (*JSONTime) Value

func (p *JSONTime) Value() (driver.Value, error)

Value insert timestamp into Mysql needs this function.

type Map

type Map map[string]interface{}

func Bean2Map

func Bean2Map(v interface{}) Map

Bean2Map ...

func StructToMap added in v1.0.0

func StructToMap(v interface{}) Map

StructToMap ...alias of Bean2Map

func (Map) ToBean

func (m Map) ToBean(v interface{}) error

ToBean ...

type QueueTask

type QueueTask struct {
	Name    string `json:"name,omitempty"`
	Data    []byte `json:"data,omitempty"`
	Retried int    `json:"retried,omitempty"`
	Group   int    `json:"group,omitempty"`
	// contains filtered or unexported fields
}

func NewQueueTask

func NewQueueTask(name string, data []byte, opt ...QueueTaskOpt) QueueTask

func (QueueTask) Copy

func (t QueueTask) Copy() QueueTask

type QueueTaskOpt

type QueueTaskOpt func(task *QueueTask)

func WithQueueTaskGroup

func WithQueueTaskGroup(group int) QueueTaskOpt

func WithQueueTaskMaxRetry added in v0.0.2

func WithQueueTaskMaxRetry(maxRetry int) QueueTaskOpt

func WithQueueTaskRetryDelayFunc added in v0.0.2

func WithQueueTaskRetryDelayFunc(retryDelayFunc func(retried int) time.Duration) QueueTaskOpt

func WithQueueTaskRunAt added in v0.0.2

func WithQueueTaskRunAt(runAt time.Time) QueueTaskOpt

type RawMessage

type RawMessage = json.RawMessage

type Slice added in v1.0.0

type Slice[T any] []T

func FromSlice added in v1.0.0

func FromSlice[T any](items []T) Slice[T]

func (Slice[T]) Find added in v1.0.0

func (s Slice[T]) Find(predicate func(T, int) bool) (result T, found bool)

Find returns the first item that matches the predicate.

func (Slice[T]) FindIndex added in v1.0.0

func (s Slice[T]) FindIndex(predicate func(T, int) bool) int

FindIndex returns the index of the first item that matches the predicate.or -1 if no item matches.

func (Slice[T]) Len added in v1.0.0

func (s Slice[T]) Len() int

func (Slice[T]) MustFind added in v1.0.0

func (s Slice[T]) MustFind(predicate func(T, int) bool) T

MustFind returns the first item that matches the predicate. If no item is found, it panics.

type Validator

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

Validator ...

func (*Validator) Constructor

func (v *Validator) Constructor()

Constructor ...

func (*Validator) Engine

func (v *Validator) Engine() interface{}

func (*Validator) New

func (v *Validator) New() *Validator

New ...

func (*Validator) TranslateZh

func (v *Validator) TranslateZh(es error) (err error)

TranslateZh ...

func (*Validator) Valid

func (v *Validator) Valid() *validator.Validate

Valid ...

func (*Validator) ValidAndTranslateZh

func (v *Validator) ValidAndTranslateZh(s interface{}) (err error)

ValidAndTranslateZh ...

func (*Validator) ValidVarWithTransZh

func (v *Validator) ValidVarWithTransZh(val interface{}, tag string) (err error)

ValidVarWithTransZh ...

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(obj interface{}) error

Jump to

Keyboard shortcuts

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