util

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2024 License: AGPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KB = 1000
	MB = 1000 * KB
	GB = 1000 * MB
	TB = 1000 * GB
	PB = 1000 * TB

	KiB = 1024
	MiB = 1024 * KiB
	GiB = 1024 * MiB
	TiB = 1024 * GiB
	PiB = 1024 * TiB
)

See: http://en.wikipedia.org/wiki/Binary_prefix

View Source
const (
	// header 占位符。用于保证实际发送 headers 的顺序
	HTTP_HEADER_PLACEHOLDER = "\n"
)

Variables

This section is empty.

Functions

func AppendUrlQueryString

func AppendUrlQueryString(url string, qs string) string

func AppendUrlQueryStringDelimiter

func AppendUrlQueryStringDelimiter(url string) string

append a proper ? or & to url

func AskYesNoConfirm added in v0.1.8

func AskYesNoConfirm(prompt string) bool

Ask user to confirm an (dangerous) action via typing yes in tty

func Assign

func Assign(dst any, src any, excludeFieldIndexes []int)

https://stackoverflow.com/questions/23350173 copy none-empty field values from src to dst. dst and src must be pointors of same type of plain struct

func AssignMap added in v0.1.8

func AssignMap[T1 comparable, T2 any](args ...map[T1]T2) map[T1]T2

similar to JavaScript's Object.assign(args[0], args[1], args[2]...), update and return args[0]. However, if args[0] is nil, create and return a new map instead; if any other arg is nil, ignore it

func BytesSize

func BytesSize(size float64) string

BytesSize returns a human-readable size in bytes, kibibytes, mebibytes, gibibytes, or tebibytes (e.g.: "44kiB", "17MiB").

func BytesSizeAround added in v0.1.9

func BytesSizeAround(size float64) string

Return at most 6 chars, e.g.: "123.1G"

func Capitalize

func Capitalize(str string) string

func ContainsI

func ContainsI(str string, substr string) bool

func CopyFile added in v0.1.9

func CopyFile(srcpath, dstpath string) (err error)

From https://stackoverflow.com/questions/21060945/simple-way-to-copy-a-file . Copy copies the contents of the file at srcpath to a regular file at dstpath. If the file named by dstpath already exists, it is truncated. The function does not copy the file mode, file permission bits, or file attributes.

func CopyMap

func CopyMap[T1 comparable, T2 any](m map[T1](T2)) map[T1](T2)

func CopySlice

func CopySlice[T any](src []T) []T

Shallow copy a slice

func CustomSize

func CustomSize(format string, size float64, base float64, _map []string) string

CustomSize returns a human-readable approximation of a size using custom format.

func DomHtml

func DomHtml(el *goquery.Selection) string

func DomRemovedSpecialCharsText

func DomRemovedSpecialCharsText(node *goquery.Selection) string

func DomRemovedSpecialCharsTextPreservingTime

func DomRemovedSpecialCharsTextPreservingTime(node *goquery.Selection) string

func DomSanitizedText

func DomSanitizedText(el *goquery.Selection) string

func DomSelectorText

func DomSelectorText(el *goquery.Selection, selector string) (text string)

DIY 了几个选择器语法(附加在标准CSS选择器字符串末尾). @text 用于选择某个 Element 里的第一个 TEXT_NODE. @after 用于选择某个 Element 后面的 TEXT_NODE.

func DomTime

func DomTime(s *goquery.Selection, location *time.Location) int64

try to extract absoulte time from DOM

func ExtractFilenameFromHttpHeader added in v0.1.9

func ExtractFilenameFromHttpHeader(header http.Header) (filename string)

Extract filename from http response "Content-Disposition: attachment; filename=..." header

func ExtractSizeStr

func ExtractSizeStr(str string) (int64, error)

func ExtractTime

func ExtractTime(str string, location *time.Location) (time int64, offset int64)

offset: if > 0, indicates the bytes offset of the end of found time string in original str

func FetchJson

func FetchJson(url string, v any, client *http.Client) error

func FetchJsonWithAzuretls added in v0.1.9

func FetchJsonWithAzuretls(url string, v any, client *azuretls.Session,
	cookie string, ua string, headers [][]string) error

func FetchUrl

func FetchUrl(url string, client *http.Client) (*http.Response, http.Header, error)

func FetchUrlWithAzuretls added in v0.1.9

func FetchUrlWithAzuretls(url string, client *azuretls.Session,
	cookie string, ua string, headers [][]string) (*azuretls.Response, http.Header, error)

func Filter

func Filter[T any](ss []T, test func(T) bool) (ret []T)

func FilterNot

func FilterNot[T any](ss []T, test func(T) bool) (ret []T)

func FindInSlice

func FindInSlice[T any](slice []T, checker func(T) bool) *T

func First added in v0.1.8

func First[T1 any, T2 any](v T1, args ...T2) T1

func FormatDate

func FormatDate(ts int64) string

func FormatDate2

func FormatDate2(ts int64) string

func FormatDuration

func FormatDuration(seconds int64) (str string)

func FormatTime

func FormatTime(ts int64) string

func FromHumanSize

func FromHumanSize(size string) (int64, error)

FromHumanSize returns an integer from a human-readable specification of a size using SI standard (e.g.: "44kB", "17MB").

func GetDurationString

func GetDurationString(seconds int64) string

func GetHttpReqHeaders added in v0.1.9

func GetHttpReqHeaders(headers [][]string, cookie string, ua string) azuretls.OrderedHeaders

func GetNewFilename

func GetNewFilename(filename string) string

return a none-existing filename

func GetStructFieldValue

func GetStructFieldValue(obj any, field string, defaultValue any) any

func GetUrlDocWithAzuretls added in v0.1.9

func GetUrlDocWithAzuretls(url string, client *azuretls.Session,
	cookie string, ua string, headers [][]string) (*goquery.Document, *azuretls.Response, error)

func GetUrlDomain

func GetUrlDomain(url string) string

return (top-level) domain of a url. e.g.: https://www.google.com/ => google.com

func GetWildcardFilenames

func GetWildcardFilenames(filestr string) []string

"*.torrent" => ["a.torrent", "b.torrent"...]. Return filestr untouched if it does not contains wildcard char. Windows cmd / powershell 均不支持命令行 *.torrent 参数扩展。必须应用自己实现。做个简易版的

func HumanSize

func HumanSize(size float64) string

HumanSize returns a human-readable approximation of a size capped at 4 valid numbers (e.g.: "2.746 MB", "796 KB").

func HumanSizeWithPrecision

func HumanSizeWithPrecision(size float64, precision int) string

HumanSizeWithPrecision allows the size to be in any precision, instead of 4 digit precision used in units.HumanSize.

func IsHexString added in v0.1.8

func IsHexString(str string, minLength int) bool

func IsHostname added in v0.1.8

func IsHostname(str string) bool

func IsIntString

func IsIntString(str string) bool

func IsPureTorrentUrl added in v0.1.9

func IsPureTorrentUrl(str string) bool

Check whether str is a url of "magnet:" or "bc://bt/" schema.

func IsTorrentUrl added in v0.1.9

func IsTorrentUrl(str string) bool

func IsUrl

func IsUrl(str string) bool

func LinkDir added in v0.1.9

func LinkDir(source string, dest string, limit int64) error

Create hardlink duplicate for source dir at dest. Recursively process all files and folders inside source. Symbolinks are ignored. For file with size < limit, create a copy instead.

func Map

func Map[T1 any, T2 any](ss []T1, mapper func(T1) T2) (ret []T2)

func MapKeys added in v0.1.8

func MapKeys[T constraints.Ordered, TV any](input map[T]TV) []T

func MapMaxElementKey

func MapMaxElementKey[TK comparable, TV constraints.Ordered](m map[TK](TV)) TK

func MatchUrlWithHostOrUrl

func MatchUrlWithHostOrUrl(urlStr string, hostOrUrl string) bool

func Now

func Now() int64

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses a duration string. A duration string is a possibly signed sequence of decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m". Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h", "d", "w".

func ParseFilenameArgs

func ParseFilenameArgs(args ...string) []string

func ParseFutureTime

func ParseFutureTime(str string) (int64, error)

func ParseInt

func ParseInt(str string) int64

func ParseLocalDateTime

func ParseLocalDateTime(str string) (int64, error)

func ParseProxyFromEnv added in v0.1.9

func ParseProxyFromEnv(urlStr string) string

Parse standard HTTP_PROXY, HTTPS_PROXY, NO_PROXY (and lowercase versions) envs, return proxy for urlStr.

func ParseRelativeUrl added in v0.1.9

func ParseRelativeUrl(relativeUrl string, baseUrl string) string

Parse a baseUrl relative relativeUrl, return absolute url. baseUrl could also be a host, in which case https schema is assumed.

func ParseTime

func ParseTime(str string, location *time.Location) (int64, error)

Parse time. Treat duration time as pasted.

func ParseTimeDuration

func ParseTimeDuration(str string) (int64, error)

Return time duration in seconds

func ParseUrlHostname

func ParseUrlHostname(urlStr string) string

func PostUrlForJson

func PostUrlForJson(url string, data url.Values, v any, client *http.Client) error

func PrintStringInWidth

func PrintStringInWidth(str string, width int64, padRight bool) (remain string)

func QuoteFilename

func QuoteFilename(str string) string

func RAMInBytes

func RAMInBytes(size string) (int64, error)

RAMInBytes parses a human-readable string representing an amount of RAM in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and returns the number of bytes, or -1 if the string is unparseable. Units are case-insensitive, and the 'b' suffix is optional.

func ResolvePointerValue

func ResolvePointerValue(obj any) any

func SanitizeText

func SanitizeText(text string) string

func Sha1

func Sha1(s []byte) string

func Sha1String

func Sha1String(s string) string

func Sleep

func Sleep(seconds int64)

func SplitCsv added in v0.1.9

func SplitCsv(str string) []string

split a csv like line to values. "a, b, c" => [a,b,c]

func String2Any

func String2Any(value string) (any, reflect.Kind)

func StringPrefixInBytes added in v0.1.9

func StringPrefixInBytes(str string, max int64) string

Return prefix of str that is at most max bytes encoded in UTF-8

func StringPrefixInWidth

func StringPrefixInWidth(str string, width int64) (string, int64)

Return prefix of string at most width and actual width. ASCII char has 1 width. CJK char has 2 width.

func StructToMap added in v0.1.8

func StructToMap(val interface{}, ignoreNoTagFields bool, ignoreEmptyFields bool) map[string]interface{}

From https://stackoverflow.com/questions/23589564/function-for-converting-a-struct-to-map-in-golang .

func UniqueSlice

func UniqueSlice[T comparable](slice []T) []T

func UniqueSliceFn

func UniqueSliceFn[TS any, TK comparable](slice []TS, keyFunc func(TS) TK) []TS

Return de-duplicated slice that every member has unique key.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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