tool

package
v0.0.0-...-092f18a Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2025 License: MIT Imports: 28 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Port    = 7304
	MPCPort = 8864
)

Variables

View Source
var (
	IP = new(macro.Once[string]).With(func() string {
		conn, err := net.DialTimeout("udp", "8.8.8.8:80", time.Second*1)
		if nil != err {
			log.Error0(err.Error())
			return "127.0.0.1"
		}
		defer log.Catch(conn.Close())
		return conn.LocalAddr().(*net.UDPAddr).IP.String()
	})
	IPHex = new(macro.Once[string]).With(func() string {
		traceId := bytes.Buffer{}
		for _, feg := range strings.Split(IP.Get(), ".") {
			digit, _ := strconv.Atoi(feg)
			traceId.WriteString(Padding(fmt.Sprintf("%X", digit), 2, "0"))
		}
		return traceId.String()
	})
	Host = new(macro.Once[string]).With(func() string {
		name, err := os.Hostname()
		if nil != err {
			log.Error0(err.Error())
		}
		return name
	})
	AvailablePort = new(macro.Once[string]).With(func() string {
		listener, err := net.Listen("tcp", ":0")
		if nil != err {
			log.Error0(err.Error())
			return "8864"
		}
		defer log.Catch(listener.Close())
		return strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)
	})
	Runtime = new(macro.Once[*Addr]).With(func() *Addr {
		return NewAddr(Anyone(macro.Runtime(), fmt.Sprintf("%s:%s", IP.Get(), AvailablePort.Get())), MPCPort)
	})
	Address = new(macro.Once[*Addrs]).With(func() *Addrs { return NewAddrs(macro.Address(), Port) })
	Name    = new(macro.Once[string]).With(func() string { return macro.Name() })
	Direct  = new(macro.Once[string]).With(func() string { return macro.Direct() })
	Subset  = new(macro.Once[string]).With(func() string { return macro.Subset() })
	Proxy   = new(macro.Once[*Addr]).With(func() *Addr { return NewAddr(macro.Proxy(), Port) })
	MDC     = new(macro.Once[[]*Addr]).With(func() []*Addr {
		var adds []*Addr
		dcs := strings.Split(macro.MDC(), ",")
		for _, dc := range dcs {
			if "" == strings.TrimSpace(dc) {
				continue
			}

			adds = append(adds, NewAddr(dc, Port))
		}
		return adds
	})
	SPA = new(macro.Once[*Addr]).With(func() *Addr { return NewAddr(Anyone(macro.SPA(), macro.Runtime()), Port) })
)
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

	// ErrInvalidBase58 is returned by ParseBase58 when given an invalid []byte
	ErrInvalidBase58 = errors.New("invalid base58")
	// ErrInvalidBase32 is returned by ParseBase32 when given an invalid []byte
	ErrInvalidBase32 = errors.New("invalid base32")
)
View Source
var Client = &http.Client{
	Transport: &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 100,
		MaxConnsPerHost:     800,
		IdleConnTimeout:     time.Minute * 10,
		DisableKeepAlives:   false,
		DisableCompression:  false,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify:     true,
			SessionTicketsDisabled: false,
			ClientSessionCache:     tls.NewLRUClientSessionCache(800),
		},
	},
}
View Source
var SharedRoutines = new(macro.Once[*ants.Pool]).With(func() *ants.Pool {
	pool, err := ants.NewPool(runtime.NumCPU()*100, ants.WithPanicHandler(func(err interface{}) {
		log.Error0("%v", err)
	}))
	if nil != err {
		panic(err.Error())
	}
	return pool
})

Functions

func Addressable

func Addressable(ctx context.Context, addr string) bool

func Anyone

func Anyone[T any](vs ...T) T

func CheckAvailable

func CheckAvailable(ctx context.Context, address string) bool

func Contains

func Contains[T comparable](vs []T, v T) bool

func ContainsAny

func ContainsAny(source string, candidates ...string) bool

ContainsAny if source contain any candidate

func Copy

func Copy(src string, dst string) error

func DecodeB64

func DecodeB64(cipher []byte) ([]byte, error)

func Distinct

func Distinct[T comparable](vs []T) []T

func DistinctCall

func DistinctCall[T any, K comparable](vs []T, deeper func(v T) K) []T

func EncodeB64

func EncodeB64(cipher []byte) ([]byte, error)

func EscapedPath

func EscapedPath(r *url.URL) string

func FieldBy

func FieldBy[T any](any interface{}, name string) interface{}

func FistLower

func FistLower(v string) string

func FistUpper

func FistUpper(v string) string

func Hash

func Hash(s string) string

func IPInHex

func IPInHex(ip string) string

func IsLocal

func IsLocal(nodeId string) bool

func IsLocalEnv

func IsLocalEnv(environ *types.Environ, nodeIds ...string) bool

func MakeDir

func MakeDir(path string) error

func MakeFile

func MakeFile(path string) error

func MapBy

func MapBy[K comparable, V any](m map[K]V, key K) (v V)

func MapValues

func MapValues[K comparable, V any, T any](m func(v V) T, dicts ...map[K]V) []T

func Merge

func Merge[K comparable, V any](dicts ...map[K]V) map[K]V

func Must

func Must(b bool)

func MustNoError

func MustNoError(err error)

func NewSpanId

func NewSpanId(spanId string, calls int) string

func NewTraceId

func NewTraceId() string

func Padding

func Padding(v string, length int, x string) string

func ReplaceName

func ReplaceName(rawName string) string

func Reverse

func Reverse[T any](vs []T) []T

func Ternary

func Ternary[T any](expr bool, left T, right T) T

func Timestamp

func Timestamp(ctx context.Context, v string) int64

func Values

func Values[K comparable, V any](dicts ...map[K]V) []V

func WithoutZero

func WithoutZero[K comparable](lists ...[]K) []K

Types

type Addr

type Addr struct {
	Host string
	Port int
}

func NewAddr

func NewAddr(addr string, dft int) *Addr

func (Addr) Empty

func (that Addr) Empty() bool

func (Addr) String

func (that Addr) String() string

type Addrs

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

func NewAddrs

func NewAddrs(addrs string, port int) *Addrs

func (*Addrs) All

func (that *Addrs) All() []string

func (*Addrs) Any

func (that *Addrs) Any() string

func (*Addrs) Available

func (that *Addrs) Available(addr string, available bool)

func (*Addrs) Many

func (that *Addrs) Many() []string

func (*Addrs) Servers

func (that *Addrs) Servers() []*StatefulServer

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 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 StatefulServer

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

Jump to

Keyboard shortcuts

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