Documentation
¶
Index ¶
- Constants
- Variables
- func Assert(ok bool)
- func AssertEqual[T comparable](t1, t2 T, tn ...T)
- func AssertError(err error)
- func BytesAsPointer(b []byte) (unsafe.Pointer, int, int)
- func BytesToString(b []byte) string
- func Compress(file []string, zipFile string) error
- func ComputeFileMd5(filename string) ([]byte, error)
- func ComputeFileSha1(filename string) ([]byte, error)
- func ComputeMD5(content io.Reader) ([]byte, error)
- func ComputeMD5Hex(content io.Reader) (string, error)
- func ComputeSHA1(content io.Reader) ([]byte, error)
- func ComputeSHA1Hex(content io.Reader) (string, error)
- func ComputeSHA256(content io.Reader) ([]byte, error)
- func ComputeSHA256Hex(content io.Reader) (string, error)
- func CopyDir(src, dst string, overwrite bool) error
- func CopyFile(src, dst string, overwrite bool) error
- func CopyFileOrDir(src, dst string, overwrite bool) error
- func CreateEmptyInstance(rType reflect.Type) interface{}
- func CreateShortcut(filename, dir string) error
- func DebugInfo() string
- func ExecutionFilePath() (string, error)
- func FileOrDirIsExist(path string) bool
- func FindStructEmptyStringField(s any, ignores map[string]bool) string
- func GenRandomAsciiString(length int) string
- func GenRandomString(charset string, length int) string
- func GenerateCPUIntensiveTask(duration time.Duration) func()
- func GenerateUniqueFilepath(filePath string) string
- func GetAllNamesInPath(path string) ([]string, error)
- func GetAllNamesRecursive(path string) ([]string, error)deprecated
- func GetCStringLen(str unsafe.Pointer) int
- func GetCurrentPath() (string, error)
- func GetExecutionPath() (string, error)
- func GetExecutionPath2() (string, error)
- func GetFileNamesRecursive(path string) ([]string, error)deprecated
- func GetFileNmaesInPath(path string) ([]string, error)
- func GetFolderNamesInPath(path string) ([]string, error)
- func GetFolderNamesRecursive(path string) ([]string, error)deprecated
- func GetFormatedTimeFromUnixMilli(rawTime int64, format string) string
- func GetFormatedTimeFromUnixMilliStr(rawTime string, format string) (string, error)
- func GetMd5(content []byte) ([]byte, error)deprecated
- func GetMd5Hex(content []byte) (string, error)deprecated
- func GetRandomUserAgent() string
- func GetSha1(data []byte) ([]byte, error)deprecated
- func GetSha256(content []byte) ([]byte, error)deprecated
- func GetYesterday() time.Time
- func GoWithRecover(fn func(), additionalHandlers ...func(recoveredErr any))
- func HexToBigInt(hex string) *big.Int
- func HexToInt(hex string) int64
- func HexToInt2(hex string) (int64, error)
- func HumanReadableByteSize[T uint64 | int64 | uint32 | int32 | uint | int](bytes T) string
- func InitConfig[T any](configFilePath string, createDefault func(path string) error, ...) (*T, error)
- func InitJsonConfig[T any](configFilePath string, createDefault func(path string) error) (*T, error)
- func IsAdmin() bool
- func IsChildDir(parent, child string) bool
- func IsChildDir2(parent, child string) bool
- func IsDir(path string) (is bool, exist bool, err error)
- func IsFile(path string) (is bool, exist bool, err error)
- func IsNil(x any) bool
- func ListAllRecursively(path string) ([]string, error)
- func ListDirsRecursively(path string) ([]string, error)
- func ListFilesRecursively(path string) ([]string, error)
- func MoveFileOrDir(src, dst string, overwrite bool) error
- func MultiReaderCloser(readers ...io.ReadCloser) io.ReadCloser
- func PressEnterKeyToContinue()
- func PressEnterKeyToContinue2(ch chan bool)
- func PressEnterKeyToContinueWithTimeout(timeout time.Duration)
- func ReadAllWithLimitBuffer(reader io.Reader, buf []byte) (n int, err error)
- func ReadLines(reader io.Reader) (lines [][]byte, err error)
- func ReadStartWithLastLine(filename string, n int) (string, error)
- func ReadTrimmedLines(reader io.Reader) (lines [][]byte, err error)
- func ReverseRead(name string, lineNum uint) ([]string, error)
- func ScanFields(lines []string, fieldSpaceLimit int, recordSpaceLimit int, ...) (fields []string, records [][]string, err error)
- func SplitBySpaceLimit(line string, spaceLimit int) []string
- func SplitBySpaceLimit2(line string, spaceLimit int) []string
- func StringAsPointer(s string) (unsafe.Pointer, int)
- func StringToBytes(s string) []byte
- func TrackTime(pre time.Time, message ...string) time.Duration
- func UnCompress(zipFile, dest string) error
- func WriteFile(filePath string, perm fs.FileMode, datas ...[]byte) error
- func WriteFile2(filePath string, data io.Reader, perm fs.FileMode) error
- type BufWriteFlushCloser
- type CopyChecker
- type Incomparable
- type LazyFileWriter
- type NoCopy
- type Pair
- type Prize
- type RateLimiter
- type Result
- type SimpleKV
- type SlidingWindowRateLimiter
- type StdBaseLogger
- type StdLogger
- type Ternary
- type WaitGroup
- type WeightedRandom
- func (wr *WeightedRandom[T]) AddPrize(item T, weight int)
- func (wr *WeightedRandom[T]) GetAllPrizes() []Prize[T]
- func (wr *WeightedRandom[T]) GetRandomPrize() Prize[T]
- func (wr *WeightedRandom[T]) GetRandomPrizeFromSlice(prizes []Prize[T]) Prize[T]
- func (wr *WeightedRandom[T]) GetRandomPrizeWithTotalWeight() (Prize[T], int64)
- func (wr *WeightedRandom[T]) GetTotalWeight() int64
- func (wr *WeightedRandom[T]) RemovePrize(item T)
- type WriteFlushCloser
Constants ¶
const DevLocalConfigFileKeyWord = ".local.dev"
const WindowsReadLnkFileErrorKeyWords = "Incorrect function"
windows下读取某些非正常快捷方式文件时会报错 read xxx : Incorrect function. 这种快捷方式使用os.Stat()查询会报告为文件夹(IsDir()会返回true), 但是使用os.ReadDir读取父文件夹来查询这个子快捷方式时,IsDir() 会返回false。
Variables ¶
var PanicHandlers = []func(any){ func(recoveredErr any) { var buf [4096]byte n := runtime.Stack(buf[:], false) msg := fmt.Sprintf("%v\n%s\n", recoveredErr, buf[:n]) _ = os.WriteFile(fmt.Sprintf("panic-%s.log", time.Now().Format("2006.01.02_15.04.05")), []byte(msg), 0644) _, _ = os.Stderr.WriteString("\x1b[31mpanic\x1b[0m: " + msg + "\n") }, }
全局默认的Panic处理
Functions ¶
func AssertEqual ¶ added in v0.2.0
func AssertEqual[T comparable](t1, t2 T, tn ...T)
func AssertError ¶ added in v0.2.0
func AssertError(err error)
func BytesToString ¶
BytesToString converts a byte slice to a string without copying. The byte slice must not be modified after the conversion. otherwise, the string may be corrupted.
func ComputeFileMd5 ¶ added in v0.3.0
func ComputeFileSha1 ¶ added in v0.3.0
func CopyDir ¶
复制文件夹到指定目录
overwrite为true时,如果目标文件夹存在名字相同的文件则覆盖, overwrite为false时,如果目标文件存在则返回错误。 dst,scr都必须是一个存在的文件夹,否则返回错误。
func CopyFile ¶
复制文件到指定目录
overwrite为true时,如果目标文件存在则覆盖, overwrite为false时,如果目标文件存在则返回错误。 dst必须是一个存在的文件夹,否则返回错误。 scr为文件的绝对或相对路径(包含文件名)。
func CopyFileOrDir ¶
复制文件或文件夹
overwrite为true时,如果目标文件存在则覆盖(dst中的目标文件或文件夹会被直接删除), overwrite为false时,如果目标文件存在则返回错误。 scr,dst 为绝对或相对路径,dst必须是一个文件夹(可以不存在)。
func CreateEmptyInstance ¶ added in v0.3.4
func CreateShortcut ¶
给目录或文件创建快捷方式(filename可以为绝对路径也可以为相对路径,dir必须是绝对路径)
func DebugInfo ¶ added in v0.6.0
func DebugInfo() string
DebugInfo collects and returns a string containing various debug information about the current program execution environment.
func ExecutionFilePath ¶
获取当前程序源代码的详细路径 D:/Go/workspace/port/network_learn/server/server.go
func FileOrDirIsExist ¶
FileOrDirIsExist Check if a file or directory exists
func FindStructEmptyStringField ¶ added in v0.3.1
查找结构体中的空字符串字段。如果找到,则返回字段名;否则返回空字符串。 string指针可以为空,但是string不可以为空。
func GenRandomAsciiString ¶ added in v0.2.1
GenRandomAsciiString generate a random string of a specified length, only containing uppercase and lowercase letters and numbers.
func GenRandomString ¶ added in v0.2.1
func GenerateCPUIntensiveTask ¶ added in v0.6.1
GenerateCPUIntensiveTask returns a function that performs a duration CPU-intensive task
func GenerateUniqueFilepath ¶ added in v0.6.0
GenerateUniqueFilepath generates a unique filepath by appending a number to the original filepath if the original filepath already exists.
func GetAllNamesInPath ¶
获取path路径下的文件(含后缀)和文件夹名称
func GetAllNamesRecursive
deprecated
func GetCStringLen ¶
func GetExecutionPath2 ¶
获取当前程序的执行路径(包含可执行文件名称) C:\Users\*\AppData\Local\Temp\*\exe\main.exe 或 .\main.exe (读取命令参数的方式)
func GetFileNamesRecursive
deprecated
func GetFileNmaesInPath ¶
获取path下所有文件名称(含后缀,不含路径)
func GetFolderNamesInPath ¶
获取path路径下的文件夹名称(不含路径)
func GetFolderNamesRecursive
deprecated
func GetFormatedTimeFromUnixMilli ¶
时间戳毫秒 -> format time(Local)。 if rawTime is "" , return current time。
func GetFormatedTimeFromUnixMilliStr ¶
时间戳毫秒 -> format time(Local)。 if rawTime is "" , return current time。
func GoWithRecover ¶ added in v0.3.0
func GoWithRecover(fn func(), additionalHandlers ...func(recoveredErr any))
func HexToBigInt ¶ added in v0.5.0
func HexToInt ¶
HexToInt converts a hexadecimal string to an int64 value. If an error occurs during conversion, the function panics.
func HumanReadableByteSize ¶ added in v0.6.0
func InitConfig ¶ added in v0.3.4
func InitConfig[T any]( configFilePath string, createDefault func(path string) error, unmarshal func(data []byte, v any) error, ) (*T, error)
InitConfig initializes a configuration object of type T from a specified file. If a development-specific configuration file exists (with a ".local.dev" suffix), it will be loaded instead. If the specified configuration file does not exist, it will be created using the provided createDefault function. The unmarshal function is used to parse the configuration file content into the object.
func InitJsonConfig ¶ added in v0.3.2
func InitJsonConfig[T any](configFilePath string, createDefault func(path string) error) (*T, error)
InitJsonConfig initializes a JSON configuration object of type T from a file. If the file doesn't exist, it creates a default file using the createDefault function (or a default create function if not provided). It uses JSON unmarshalling to parse the file content into the config object.
func IsAdmin ¶
func IsAdmin() bool
IsAdmin checks if the current process is running with administrative privileges.
func IsChildDir2 ¶
判断child是否是parent的子文件夹(为了性能只是简单的判断前缀,需要保证路径分隔符一致)
func ListAllRecursively ¶ added in v0.6.1
ListAllRecursively recursively retrieves all paths under the specified path, including files and directories. If the path is a file, it returns the path itself. The returned paths are either absolute or relative based on the input path.
func ListDirsRecursively ¶ added in v0.6.1
ListDirsRecursively recursively retrieves all directories under the specified path, including subdirectories. If the path is a directory, it returns the path itself. The returned directory paths are either absolute or relative based on the input path.
func ListFilesRecursively ¶ added in v0.6.1
ListFilesRecursively recursively retrieves all files under the specified path, including files in subdirectories. If the path is a file, it returns the path itself. The returned file paths are either absolute or relative based on the input path.
func MoveFileOrDir ¶
移动文件或文件夹到指定目录
overwrite为true时,如果目标文件存在则覆盖(dst中的目标文件或文件夹会被直接删除), overwrite为false时,如果目标文件存在则返回错误。 dst必须是一个存在的文件夹,否则返回错误。 scr为的绝对或相对路径。
func MultiReaderCloser ¶ added in v0.5.0
func MultiReaderCloser(readers ...io.ReadCloser) io.ReadCloser
func PressEnterKeyToContinue ¶
func PressEnterKeyToContinue()
func PressEnterKeyToContinue2 ¶
func PressEnterKeyToContinue2(ch chan bool)
func PressEnterKeyToContinueWithTimeout ¶
Press Enter Key to Continue with Timeout,超时则退出程序
func ReadAllWithLimitBuffer ¶ added in v0.3.5
ReadAllWithLimitBuffer reads from reader until EOF or an error occurs. If buf is full before EOF, ReadAllWithLimitBuffer returns an error.
func ReadStartWithLastLine ¶
读取倒数第n行(n从1开始), 若n大于文件行数则返回错误io.EOF。
func ReadTrimmedLines ¶
ReadTrimmedLines 从给定的 io.Reader 中读取内容,并按行分割成字节切片。 开头和结尾的空白行将被去除。 返回值 lines 是一个二维字节切片,每个元素代表一行的内容。
func ReverseRead ¶
从文件末尾按行读取文件。 name:文件路径 lineNum:读取行数(超过文件行数则读取全文)。 最后一行为空也算读取了一行,会返回此行为空串,若全是空格也会原样返回。 返回的每一行都不包含换行符号。
func ScanFields ¶
func ScanFields( lines []string, fieldSpaceLimit int, recordSpaceLimit int, fieldKeyWords map[string]func(string) bool, ) (fields []string, records [][]string, err error)
ScanFields 函数的作用是解析一组文本行(lines),将第一行作为字段名称(fields)提取, 并将剩余的行解析为记录(records),每条记录是字段值的集合。 这个函数可以处理有限数量的空格字符来分隔记录中的字段。 函数的参数: lines: 一个字符串切片,包含要解析的文本行。 recordSpaceLimit: 一个整数,指定字段之间的最小空格数来认为字段是分开的。 如果为0,则使用任意数量的空格来分隔字段。 需要保证第一行是字段名, 且后面每行都是有效的记录。
例如,下面的文本行: ¶
Name Access Availability BlockSize
C: 3 0 4096
D: 3 4096
E: 3 1 4096
F: 1 4096
将被解析为:
fields = ["Name", "Access", "Availability", "BlockSize"]
records = [ ["C:", "3", "0", "4096"], ["D:", "3", "", "4096"], ["E:", "3", "1", "4096"], ["F:", "", "1", "4096"],
]
func SplitBySpaceLimit ¶
func SplitBySpaceLimit2 ¶
func StringToBytes ¶
func TrackTime ¶ added in v0.3.1
TrackTime calculates the elapsed time since the given time and prints it.
Usage:
defer TrackTime(time.Now())
Types ¶
type BufWriteFlushCloser ¶
type BufWriteFlushCloser struct {
// contains filtered or unexported fields
}
Close automatically Flush and then Close
func NewBufWriteCloser ¶
func NewBufWriteCloser(w io.WriteCloser) *BufWriteFlushCloser
func NewBufWriteCloserSize ¶
func NewBufWriteCloserSize(w io.WriteCloser, size int) *BufWriteFlushCloser
func (*BufWriteFlushCloser) Close ¶
func (b *BufWriteFlushCloser) Close() error
Close closes the BufWriteFlushCloser, flushing the buffer and closing the underlying writer.
func (*BufWriteFlushCloser) Flush ¶
func (b *BufWriteFlushCloser) Flush() error
type CopyChecker ¶ added in v0.2.0
type CopyChecker uintptr
CopyChecker holds back pointer to itself to detect object copying.
func (*CopyChecker) Check ¶ added in v0.2.0
func (c *CopyChecker) Check() error
Check checks if the CopyChecker object has been copied. The Check method records its address the first time it is called and checks whether its address has changed the next time it is called. The Check method is thread-safe and can be called from multiple goroutines.
type Incomparable ¶ added in v0.6.1
type Incomparable [0]func()
Incomparable is a zero-width, non-comparable type. Adding it to a struct makes that struct also non-comparable, and generally doesn't add any size (as long as it's first).
type LazyFileWriter ¶ added in v0.5.1
type LazyFileWriter struct {
// contains filtered or unexported fields
}
func NewLazyFileWriter ¶ added in v0.5.1
func NewLazyFileWriter(filePath string) *LazyFileWriter
NewLazyFileWriter creates a new LazyFileWriter with the given file path
func (*LazyFileWriter) Close ¶ added in v0.5.1
func (w *LazyFileWriter) Close() error
Close closes the file. Close will return an error if it has already been called.
func (*LazyFileWriter) File ¶ added in v0.5.1
func (w *LazyFileWriter) File() *os.File
File returns the file handle
func (*LazyFileWriter) IsCreated ¶ added in v0.5.1
func (w *LazyFileWriter) IsCreated() bool
IsCreated checks if the file has been created/opened
func (*LazyFileWriter) Name ¶ added in v0.5.1
func (w *LazyFileWriter) Name() string
Name returns the base name of the file
func (*LazyFileWriter) Path ¶ added in v0.5.1
func (w *LazyFileWriter) Path() string
func (*LazyFileWriter) Sync ¶ added in v0.5.1
func (w *LazyFileWriter) Sync() error
Sync flushes file's in-memory state to disk
type NoCopy ¶ added in v0.2.0
type NoCopy struct{}
NoCopy may be added to structs which must not be copied after the first use.
See https://golang.org/issues/8005#issuecomment-190753527 for details.
Note that it must not be embedded, due to the Lock and Unlock methods.
type Prize ¶ added in v0.6.0
type Prize[T comparable] struct { Item T Weight int64 }
Prize represents a prize with a weight
type RateLimiter ¶ added in v0.6.0
type RateLimiter struct {
// contains filtered or unexported fields
}
func NewRateLimiter ¶ added in v0.6.0
func NewRateLimiter(limit int, windowSize time.Duration, subWindowNum int) *RateLimiter
NewRateLimiter creates a new RateLimiter.
Example:
// 100 requests per minute, divided into 6 sub-windows NewRateLimiter(100, time.Minute, 6)
func (*RateLimiter) Allow ¶ added in v0.6.0
func (rl *RateLimiter) Allow(userID string) bool
func (*RateLimiter) CancelCleanup ¶ added in v0.6.0
func (rl *RateLimiter) CancelCleanup()
type SimpleKV ¶
type SimpleKV struct {
// contains filtered or unexported fields
}
func NewSimpleKV ¶
type SlidingWindowRateLimiter ¶ added in v0.6.0
type SlidingWindowRateLimiter struct {
// contains filtered or unexported fields
}
func NewSlidingWindowRateLimiter ¶ added in v0.6.0
func NewSlidingWindowRateLimiter(limit int, windowSize time.Duration, subWindowNum int) *SlidingWindowRateLimiter
func (*SlidingWindowRateLimiter) Allow ¶ added in v0.6.0
func (rl *SlidingWindowRateLimiter) Allow() bool
type StdBaseLogger ¶
type StdLogger ¶
type StdLogger interface {
StdBaseLogger
Panicf(string, ...interface{})
Panicln(...interface{})
Tracef(string, ...interface{})
Traceln(...interface{})
}
type Ternary ¶ added in v0.5.0
type Ternary int8
func DirIsExist ¶ added in v0.5.0
DirIsExist Check if a directory exists, return True, False, or Unknown
func FileIsExist ¶
FileIsExist Check if a file exists, return True, False, or Unknown
type WaitGroup ¶ added in v0.3.0
type WaitGroup struct {
// contains filtered or unexported fields
}
type WeightedRandom ¶ added in v0.6.0
type WeightedRandom[T comparable] struct { // contains filtered or unexported fields }
WeightedRandom holds the prizes and their cumulative distribution
func NewWeightedRandom ¶ added in v0.6.0
func NewWeightedRandom[T comparable]() *WeightedRandom[T]
func (*WeightedRandom[T]) AddPrize ¶ added in v0.6.0
func (wr *WeightedRandom[T]) AddPrize(item T, weight int)
AddPrize adds a new prize with a specified weight to the collection.
func (*WeightedRandom[T]) GetAllPrizes ¶ added in v0.6.0
func (wr *WeightedRandom[T]) GetAllPrizes() []Prize[T]
GetAllPrizes returns a copy of all prizes.
func (*WeightedRandom[T]) GetRandomPrize ¶ added in v0.6.0
func (wr *WeightedRandom[T]) GetRandomPrize() Prize[T]
GetRandomPrize returns a random prize based on weights.
func (*WeightedRandom[T]) GetRandomPrizeFromSlice ¶ added in v0.6.0
func (wr *WeightedRandom[T]) GetRandomPrizeFromSlice(prizes []Prize[T]) Prize[T]
GetRandomPrizeFromSlice selects a random prize from a slice based on weights. It panics if no prize is found.
func (*WeightedRandom[T]) GetRandomPrizeWithTotalWeight ¶ added in v0.6.0
func (wr *WeightedRandom[T]) GetRandomPrizeWithTotalWeight() (Prize[T], int64)
GetRandomPrizeWithTotalWeight returns a random prize and the total weight.
func (*WeightedRandom[T]) GetTotalWeight ¶ added in v0.6.0
func (wr *WeightedRandom[T]) GetTotalWeight() int64
GetTotalWeight returns the total weight of all prizes.
func (*WeightedRandom[T]) RemovePrize ¶ added in v0.6.0
func (wr *WeightedRandom[T]) RemovePrize(item T)
RemovePrize removes a prize from the collection.
type WriteFlushCloser ¶
type WriteFlushCloser interface {
io.WriteCloser
Flush() error
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Record a few snippets of code
|
Record a few snippets of code |
|
watch_demo
command
|
|
|
usb
|
|
|
gousb/example1
command
|
|
|
gousb/example2
command
|
|
|
hid
HID package to access Human Interface Devices.
|
HID package to access Human Interface Devices. |
|
hid/example
command
|
|
|
serial/example1
command
|
|
|
usbdrivedetector
Package usbdrivedetector detects all USB storage devices connected to a computer.
|
Package usbdrivedetector detects all USB storage devices connected to a computer. |
|
usbdrivedetector/example
command
|
|
|
example
command
|
|
|
example2
command
|