vege

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 14, 2026 License: MIT Imports: 39 Imported by: 1

Documentation

Index

Constants

View Source
const (
	IPSB4URL = `http://api-ipv4.ip.sb/ip`
	IPSB6URL = `http://api-ipv6.ip.sb/ip`
)
View Source
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
)
View Source
const (
	IPIP4URL = `http://myip.ipip.net/s`
)

Variables

View Source
var (
	CertName = "cert.pem"
	KeyName  = "key.pem"
)
View Source
var HttpClient = &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
		DisableKeepAlives: true,
	},
}

InsecureSkipVerify DisableKeepAlives true

View Source
var SkipHttpsClient = &http.Client{Transport: &http.Transport{
	TLSClientConfig: &tls.Config{
		InsecureSkipVerify: true,
	},
}}

Functions

func CheckBySalt

func CheckBySalt(check, hash, salt string) bool

CheckBySalt check HmacHashWithSalt

func CostTimeDur

func CostTimeDur(fn func()) time.Duration

计算fn耗时

func CountTotalPage added in v1.1.6

func CountTotalPage(total int64, size int) int

CountTotalPage 计算总页数

func DeepCopyByGob

func DeepCopyByGob(src, dst any) error

gob实现 dst必须是指针

func DeepCopyByJson

func DeepCopyByJson(src, dst any) error

json实现 dst必须是指针

func DelRightRN added in v1.1.3

func DelRightRN(item string, r string, n int) string

DelRightRN 移除字符串 item 中最后 n 个特定字符 r,并返回修改后的字符串。 如果 item 中 r 出现的次数小于 n,则不进行修改。 参数:

item: 要处理的字符串
r: 要移除的特定字符
n: 要移除的 r 的数量

返回值:

修改后的字符串

func DiffField

func DiffField[T comparable](o, n T) (t T)

比较old new,相等返回类型零值,不相等返回new

func GetLocalIpv4ByUdp

func GetLocalIpv4ByUdp() (ip string, err error)

GetLocalIpv4ByUdp 获取 localIp by net.Dial("udp", "8.8.8.8:53")

func GetLocalIpv4List

func GetLocalIpv4List() ([]string, error)

GetLocalIpv4List 获取所有非lo的网卡ip

func GetMacAddr added in v1.1.0

func GetMacAddr() (map[string]string, error)

GetMacAddr 获取本机的MAC地址

func GetMapNestedValue added in v1.1.11

func GetMapNestedValue(m map[string]any, keys ...string) (any, bool)

获取深层 value 的通用函数

func GetPubIpVipip added in v1.1.0

func GetPubIpVipip(typ IpTyp) (ip string, err error)

GetPubIpVipip 通过ip.sb获取公网ip 仅支持ipv4

func GetPubIpVipsb added in v1.1.0

func GetPubIpVipsb(typ IpTyp) (ip string, err error)

GetPubIpVipsb 通过ip.sb获取公网ip

func HasNum

func HasNum(s string) bool

HasNum s包含数字字符返回true

func HmacHashWithSalt added in v1.1.0

func HmacHashWithSalt(ps, salt string) string

HmacHashWithSalt hmac sha2 and salt make hash

func If added in v1.2.0

func If[T any](condition bool, trueVal, falseVal T) T

If returns trueVal if condition is true, otherwise falseVal. 场景:由行三元运算符: vege.If(age > 18, "Adult", "Minor")

func IfEx

func IfEx[T any](boolExpr bool, trueReturn, falseReturn T) T

IfEx if 实现的三元表达式

func IfPtr added in v1.2.0

func IfPtr[T any](condition bool, trueVal, falseVal T) *T

IfPtr returns &trueVal if condition is true, otherwise &falseVal.

func Ip2Long added in v1.1.0

func Ip2Long(str string) uint32

Ip2Long 将 IPv4 字符串形式转为 uint32

func IsNilOrZero added in v1.2.0

func IsNilOrZero[T comparable](ptr *T) bool

IsNilOrZero checks if a pointer is nil OR if it points to a zero value.

func ItemIsInSlice

func ItemIsInSlice[T comparable](item T, slice []T) bool

func JsonMarshal

func JsonMarshal(v any) ([]byte, error)

func JsonMarshalToString

func JsonMarshalToString(v any) (string, error)

func JsonMarshalToStringV2

func JsonMarshalToStringV2(v any) (string, error)

func JsonMarshalV2

func JsonMarshalV2(v any) ([]byte, error)

func JsonUnmarshal

func JsonUnmarshal(data []byte, v any) error

func JsonUnmarshalFromString

func JsonUnmarshalFromString(str string, v any) error

func JsonUnmarshalFromStringV2

func JsonUnmarshalFromStringV2(str string, v any) error

func JsonUnmarshalV2

func JsonUnmarshalV2(data []byte, v any) error

func MapClear

func MapClear[M ~map[K]V, K comparable, V any](m M)

MapClear removes all entries from m, leaving it empty.

func MapClone

func MapClone[M ~map[K]V, K comparable, V any](m M) M

MapClone returns a copy of m. This is a shallow clone: the new keys and values are set using ordinary assignment.

func MapCopy

func MapCopy[M1 ~map[K]V, M2 ~map[K]V, K comparable, V any](dst M1, src M2)

MapCopy copies all key/value pairs in src adding them to dst. When a key in src is already present in dst, the value in dst will be overwritten by the value associated with the key in src.

func MapDeleteFunc

func MapDeleteFunc[M ~map[K]V, K comparable, V any](m M, del func(K, V) bool)

MapDeleteFunc deletes any key/value pairs from m for which del returns true.

func MapEqual

func MapEqual[M1, M2 ~map[K]V, K, V comparable](m1 M1, m2 M2) bool

MapEqual reports whether two maps contain the same key/value pairs. MapValues are compared using ==.

func MapEqualFunc

func MapEqualFunc[M1 ~map[K]V1, M2 ~map[K]V2, K comparable, V1, V2 any](m1 M1, m2 M2, eq func(V1, V2) bool) bool

MapEqualFunc is like MapEqual, but compares values using eq. MapKeys are still compared with ==.

func MapKeys

func MapKeys[M ~map[K]V, K comparable, V any](m M) []K

MapKeys returns the keys of the map m. The keys will be in an indeterminate order.

func MapPtr2Value added in v1.2.0

func MapPtr2Value[K comparable, V any](m map[K]*V) map[K]V

MapPtr2Value converts map[K]*V to map[K]V.

func MapToObj

func MapToObj(m map[string]any, obj any) error

MapToObj map[string] interface ---> obj

func MapValue2Ptr added in v1.2.0

func MapValue2Ptr[K comparable, V any](m map[K]V) map[K]*V

MapValue2Ptr converts map[K]V to map[K]*V.

func MapValues

func MapValues[M ~map[K]V, K comparable, V any](m M) []V

MapValues returns the values of the map m. The values will be in an indeterminate order.

func NewGoogleUUID added in v1.0.20

func NewGoogleUUID() string

google uuid v4

func ObjToMap

func ObjToMap(obj any, m *map[string]any) error

ObjToMap obj ---> map[string] interface

func PanicIfErr

func PanicIfErr(err error)

func PanicToErr

func PanicToErr(fn func()) (err error)

func ParseDateStr added in v1.1.11

func ParseDateStr(dateStr string) (time.Time, error)

ParseDateStr 解析常见的日期格式字符串到 time.Time

func PathExists added in v1.1.4

func PathExists(path string) (bool, error)

判断 file 、dir 是否存在

func Ptr2Value

func Ptr2Value[T any](ptr *T) T

Ptr2Value returns ptr's value; if ptr==nil, return zero value of T.

func Ptr2ValueWithDefault added in v1.2.0

func Ptr2ValueWithDefault[T any](ptr *T, defaultVal T) T

Ptr2ValueWithDefault returns ptr's value; if ptr==nil, return the specific defaultVal. 场景:如果指针为空,我想返回 -1 或者 "unknown",而不是 0 或 ""。

func PtrOrNil added in v1.2.0

func PtrOrNil[T comparable](v T) *T

PtrOrNil returns nil if v is the zero value of T, otherwise returns &v. 场景:在更新数据库时,如果字段是零值(如空字符串),不想传空指针,而是传 nil 以避免覆盖。 注意:T 必须是可比较类型 (comparable)。

func RandBytesMask

func RandBytesMask(n int) []byte

func RandCodeMask

func RandCodeMask(n int) string

func RandIdMask

func RandIdMask(n int) string

func RandSelfDefMask

func RandSelfDefMask(n int, bs string) string

func RandStringMask

func RandStringMask(n int) string

func RemoteIp

func RemoteIp(req *http.Request) string

RemoteIp 返回远程客户端的 IP,如 192.168.1.1

func RemoveInvalidParentheses

func RemoveInvalidParentheses(s string, pair [2]rune) string

RemoveInvalidParentheses 去除s中不成对的括号,pair为成对的括号

func ReplaceLast added in v1.1.4

func ReplaceLast(s, old, new string) string

ReplaceLast 替换字符串最后一个匹配项

func RetryFn added in v1.1.11

func RetryFn(cfg RetryConfig, fn func() error) (err error)

func RuneIndex added in v1.1.6

func RuneIndex(src, sub []rune) int

RuneIndex 查找子切片在源切片中的 unicode索引位置

func SliceEqual

func SliceEqual[T comparable](s1, s2 []T) bool

func SliceGroupsOf

func SliceGroupsOf[T any](arr []T, num int64) [][]T

func SliceIsInSlice

func SliceIsInSlice[T comparable](item []T, slice []T) bool

func SlicePtr2Value added in v1.2.0

func SlicePtr2Value[T any](s []*T) []T

SlicePtr2Value converts a slice of pointers to a slice of values. Nil pointers in the slice will be converted to zero values. 场景:处理 API 响应,将 []*User 转为 []User。

func SliceSub

func SliceSub[T comparable](s1 []T, s2 []T) []T

func SliceUnique

func SliceUnique[T comparable](arr []T) []T

func SliceValue2Ptr added in v1.2.0

func SliceValue2Ptr[T any](s []T) []*T

SliceValue2Ptr converts a slice of values to a slice of pointers. 场景:批量构造数据库模型或 API 请求体。

func StringsContainsSlice added in v1.1.4

func StringsContainsSlice(s string, arr []string) bool

StringsContainsSlice 展开arr判断s是否Contains

func TlsCertGenerateToFile

func TlsCertGenerateToFile(path string) error

TlsCertGenerateToFile 生成自签tls证书 cert.pem key.pem 到指定文件夹中

func TlsCertGenerateToMap

func TlsCertGenerateToMap() (cert map[string]string, err error)

TlsCertGenerateToMap 生成自签tls证书 cert.pem key.pem 到map

func ValidateEmail added in v1.1.11

func ValidateEmail(email string) bool

func ValidatePhone added in v1.1.11

func ValidatePhone(phone string) bool

func Value2Ptr

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

Value2Ptr returns &v.

Types

type IpTyp added in v1.1.0

type IpTyp uint8
const (
	IpV4Typ IpTyp = iota
	IpV6Typ
)

type Quit

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

func NewQuit

func NewQuit() *Quit

func (*Quit) Close

func (q *Quit) Close() error

func (*Quit) WaitCloseWithFn

func (q *Quit) WaitCloseWithFn(fn func())

type Rate

type Rate struct {
	ratelimit.Limiter
}

Rate 基于 "go.uber.org/ratelimit" 的漏桶算法限流器的封装 固定速率执行业务函数

func NewRateLeakyBucket

func NewRateLeakyBucket(n int64) *Rate

创建QPS为n的限流器

func (*Rate) RateLimitDo

func (r *Rate) RateLimitDo(fn func())

定速执行业务函数

type RetryConfig added in v1.1.11

type RetryConfig struct {
	Count    int
	SleepDur time.Duration
	Log      func(msg ...any)
}

type WorkerPool

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

WorkerPool is a collection of goroutines, where the number of concurrent goroutines processing requests does not exceed the specified maximum.

func NewWorkerPool

func NewWorkerPool(maxWorkers int) *WorkerPool

NewWorkerPool creates and starts a pool of worker goroutines.

The maxWorkers parameter specifies the maximum number of workers that can execute tasks concurrently. When there are no incoming tasks, workers are gradually stopped until there are no remaining workers.

func (*WorkerPool) Pause

func (p *WorkerPool) Pause(ctx context.Context)

Pause causes all workers to wait on the given Context, thereby making them unavailable to run tasks. Pause returns when all workers are waiting. Tasks can continue to be queued to the workerpool, but are not executed until the Context is canceled or times out.

Calling Pause when the worker pool is already paused causes Pause to wait until all previous pauses are canceled. This allows a goroutine to take control of pausing and unpausing the pool as soon as other goroutines have unpaused it.

When the workerpool is stopped, workers are unpaused and queued tasks are executed during StopWait.

func (*WorkerPool) Size

func (p *WorkerPool) Size() int

Size returns the maximum number of concurrent workers.

func (*WorkerPool) Stop

func (p *WorkerPool) Stop()

Stop stops the worker pool and waits for only currently running tasks to complete. Pending tasks that are not currently running are abandoned. Tasks must not be submitted to the worker pool after calling stop.

Since creating the worker pool starts at least one goroutine, for the dispatcher, Stop() or StopWait() should be called when the worker pool is no longer needed.

func (*WorkerPool) StopWait

func (p *WorkerPool) StopWait()

StopWait stops the worker pool and waits for all queued tasks tasks to complete. No additional tasks may be submitted, but all pending tasks are executed by workers before this function returns.

func (*WorkerPool) Stopped

func (p *WorkerPool) Stopped() bool

Stopped returns true if this worker pool has been stopped.

func (*WorkerPool) Submit

func (p *WorkerPool) Submit(task func())

Submit enqueues a function for a worker to execute.

Any external values needed by the task function must be captured in a closure. Any return values should be returned over a channel that is captured in the task function closure.

Submit will not block regardless of the number of tasks submitted. Each task is immediately given to an available worker or to a newly started worker. If there are no available workers, and the maximum number of workers are already created, then the task is put onto a waiting queue.

When there are tasks on the waiting queue, any additional new tasks are put on the waiting queue. Tasks are removed from the waiting queue as workers become available.

As long as no new tasks arrive, one available worker is shutdown each time period until there are no more idle workers. Since the time to start new goroutines is not significant, there is no need to retain idle workers indefinitely.

func (*WorkerPool) SubmitBlockBySize

func (p *WorkerPool) SubmitBlockBySize(task func())

when queue length equal maximum block

func (*WorkerPool) SubmitWait

func (p *WorkerPool) SubmitWait(task func())

SubmitWait enqueues the given function and waits for it to be executed.

func (*WorkerPool) WaitingQueueSize

func (p *WorkerPool) WaitingQueueSize() int

WaitingQueueSize returns the count of tasks in the waiting queue.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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