amoy

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2023 License: MIT Imports: 48 Imported by: 14

README

amoy

go.dev reference

Just another collection of Go utilities among yet another packages.

Telling a programmer there's already a library to do X is like telling a songwriter there's already a song about love.

Documentation

Index

Constants

View Source
const (
	Byte = 1 << (iota * 10)
	KiByte
	MiByte
	GiByte
	TiByte
	PiByte
	EiByte
)

IEC Sizes. kibis of bits

View Source
const (
	IByte = 1
	KByte = IByte * 1000
	MByte = KByte * 1000
	GByte = MByte * 1000
	TByte = GByte * 1000
	PByte = TByte * 1000
	EByte = PByte * 1000
)

SI Sizes.

View Source
const (
	// MinUint the smallest possible value of uint.
	MinUint = uint(0)
	// MaxUint the largest possible value of uint.
	MaxUint = ^uint(0)

	// MinUint32 the smallest possible value of uint32.
	MinUint32 = uint32(0)
	// MaxUint32 the largest possible value of uint32.
	MaxUint32 = ^uint32(0)

	// MinUint64 the smallest possible value of uint64.
	MinUint64 = uint64(0)
	// MaxUint64 the largest possible value of uint64.
	MaxUint64 = ^uint64(0)

	// MinInt the smallest possible value of int.
	MinInt = -MaxInt - 1
	// MaxInt the largest possible value of int.
	MaxInt = int(^uint(0) >> 1)

	// MinInt32 the smallest possible value of int.
	MinInt32 = -MaxInt32 - 1
	// MaxInt32 the largest possible value of int.
	MaxInt32 = int32(^uint32(0) >> 1)

	// MinInt64 the smallest possible value of int.
	MinInt64 = -MaxInt64 - 1
	// MaxInt64 the largest possible value of int.
	MaxInt64 = int64(^uint64(0) >> 1)
)
View Source
const (
	Nanosecond  time.Duration = 1
	Microsecond               = 1000 * Nanosecond
	Millisecond               = 1000 * Microsecond
	Second                    = 1000 * Millisecond
	Minute                    = 60 * Second
	Hour                      = 60 * Minute
	Day                       = 24 * Hour
	Week                      = 7 * Day
	Year                      = 365 * Day
)

Common durations. Inherited from libexec/src/time/time.go

Variables

View Source
var (
	// ZeroDate is the default Date with zero values.
	ZeroDate = Date{}

	// MinDate is the minimum Date value supported.
	MinDate = Date{1, 1, 1}

	// MaxDate is the maximum Date value supported.
	MaxDate = Date{9999, 12, 31}
)
View Source
var (
	// PositiveInfinity indicates the positive infinity value.
	PositiveInfinity = math.Inf(1)
	// NegativeInfinity indicates the negative infinity value.
	NegativeInfinity = math.Inf(-1)
)
View Source
var (

	// Simple style functions
	StyleIndex     = makeFlexFgStyle("238", "250")
	StyleMessage   = makeFgStyle("200")
	StyleName      = makeFgStyle("207")
	StyleDate      = makeFgStyle("82")
	StyleHighlight = makeFgStyle("227")
	StyleLabel     = makeFgStyle("51")
	StyleAmount    = makeFgStyle("207")
	StyleDot       = colorFg("•", "236")
	StyleDash      = colorFg("-", "236")
	StyleLineBreak = colorFg(strings.Repeat("█", lineBreakLength), "246")
)
View Source
var (
	// ZeroDuration is a zero-value for time.Duration.
	ZeroDuration time.Duration

	// ZeroTime is a zero-value for time.Time.
	ZeroTime = time.Time{}
)
View Source
var DiscardWriteCloser io.WriteCloser = discardCloser{}

DiscardWriteCloser is a WriteCloser on which all Write calls succeed without doing anything.

View Source
var DiscardWriter = io.Discard

DiscardWriter is a Writer on which all Write calls succeed without doing anything.

View Source
var EmptyStr string

EmptyStr is the missing empty string for Go :)

View Source
var (
	// ErrNoPipeData is returned when no data was read from the stdin pipe.
	ErrNoPipeData = errors.New("amoy: no pipe data")
)
View Source
var (

	// ErrWaitTimeout indicates timeout after waiting.
	ErrWaitTimeout = errors.New("amoy: wait timeout")
)
View Source
var Now = time.Now

Now returns the current local time. This value is simply time.Now for consistency.

View Source
var (
	// QuitRead indicates the arbitrary error means to quit from reading.
	QuitRead = errors.New("amoy: quit read by line")
)
View Source
var (
	// QuitUnzip indicates the arbitrary error means to quit from unzip.
	QuitUnzip = errors.New("amoy: quit unzip file")
)
View Source
var (
	// Version is the current version of amoy.
	Version = "v0.2.1"
)

Functions

func AccumulatedChannel added in v0.1.3

func AccumulatedChannel(inCh <-chan []byte, size int) <-chan []byte

AccumulatedChannel returns a channel that accumulates values from given channel.

func AfterNow

func AfterNow(t time.Time) bool

AfterNow indicates if the given time is after current time.

func AppStartTime added in v0.1.1

func AppStartTime() time.Time

AppStartTime returns time when the app started.

func AppUpTime added in v0.1.1

func AppUpTime() time.Duration

AppUpTime returns time elapsed since the app started.

func AppendFileBytes added in v0.1.0

func AppendFileBytes(path string, data []byte) error

AppendFileBytes writes the given data to the end of a file.

func AppendFileLines added in v0.1.0

func AppendFileLines(path string, lines []string) error

AppendFileLines appends the given lines to the end of a text file.

func AppendFileString added in v0.1.0

func AppendFileString(path string, content string) error

AppendFileString appends the given content string to the end of a file.

func Atof32 added in v0.1.10

func Atof32(s string) (float32, error)

Atof32 is equivalent to strconv.ParseFloat(s, 32).

func Atof64 added in v0.1.10

func Atof64(s string) (float64, error)

Atof64 is equivalent to strconv.ParseFloat(s, 64).

func Atoi

func Atoi(s string) (int, error)

Atoi is equivalent to strconv.Atoi(s).

func Atoi16 added in v0.1.10

func Atoi16(s string) (int16, error)

Atoi16 is equivalent to strconv.ParseInt(s, 10, 16).

func Atoi32

func Atoi32(s string) (int32, error)

Atoi32 is equivalent to strconv.ParseInt(s, 10, 32).

func Atoi64

func Atoi64(s string) (int64, error)

Atoi64 is equivalent to strconv.ParseInt(s, 10, 64).

func Atoi8 added in v0.1.10

func Atoi8(s string) (int8, error)

Atoi8 is equivalent to strconv.ParseInt(s, 10, 8).

func Atou

func Atou(s string) (uint, error)

Atou is equivalent to strconv.ParseUint(s, 10, 0).

func Atou16 added in v0.1.10

func Atou16(s string) (uint16, error)

Atou16 is equivalent to strconv.ParseUint(s, 10, 16).

func Atou32

func Atou32(s string) (uint32, error)

Atou32 is equivalent to strconv.ParseUint(s, 10, 32).

func Atou64

func Atou64(s string) (uint64, error)

Atou64 is equivalent to strconv.ParseUint(s, 10, 64).

func Atou8 added in v0.1.10

func Atou8(s string) (uint8, error)

Atou8 is equivalent to strconv.ParseUint(s, 10, 8).

func BackOffRetry

func BackOffRetry(work func() error, times uint, delay time.Duration) error

BackOffRetry retries to execute given function with exponential backoff delay.

func BackOffRetryIf

func BackOffRetryIf(work func() error, retryIf RetryIfFunc, times uint, delay time.Duration) error

BackOffRetryIf retries to execute given function with exponential backoff delay if condition meets.

func BeforeNow

func BeforeNow(t time.Time) bool

BeforeNow indicates if the given time is before current time.

func BlockForever added in v0.1.3

func BlockForever()

BlockForever blocks current goroutine forever.

func BoolPtr added in v0.2.3

func BoolPtr(b bool) *bool

BoolPtr returns a pointer to the bool value passed in.

func BytePtr added in v0.2.3

func BytePtr(b byte) *byte

BytePtr returns a pointer to the byte value passed in.

func ChangeDir

func ChangeDir(path string)

ChangeDir changes the current working directory.

func CharBool added in v0.1.5

func CharBool(yes bool) string

CharBool returns a Unicode char representing the given boolean value.

func ChooseWeightStrMap added in v0.0.16

func ChooseWeightStrMap(weightMap map[string]float64) string

ChooseWeightStrMap selects a random string key according to weights in value, or panics for invalid weights or internal errors.

func Complex128Ptr added in v0.2.3

func Complex128Ptr(c complex128) *complex128

Complex128Ptr returns a pointer to the complex128 value passed in.

func Complex64Ptr added in v0.2.3

func Complex64Ptr(c complex64) *complex64

Complex64Ptr returns a pointer to the complex64 value passed in.

func ComputeSI

func ComputeSI(input float64) (float64, string)

ComputeSI finds the most appropriate SI prefix for the given number and returns the prefix along with the value adjusted to be within that prefix.

See also: SI, ParseSI.

e.g. ComputeSI(2.2345e-12) -> (2.2345, "p")

func ContainsChinese added in v0.1.4

func ContainsChinese(s string) bool

ContainsChinese returns true if the string contains Chinese characters (Hanzhi).

func ContainsJapanese added in v0.1.4

func ContainsJapanese(s string) bool

ContainsJapanese returns true if the string contains Japanese characters (Kanji, Hiragana, Katakana).

func ContainsKorean added in v0.1.4

func ContainsKorean(s string) bool

ContainsKorean returns true if the string contains Korean characters (Hangul).

func CountDigit added in v0.1.2

func CountDigit(num int) int

CountDigit returns the number of digits of a number.

func CountFileLines added in v0.1.0

func CountFileLines(path string) (count int, err error)

CountFileLines counts all lines from the given file (the line ending chars are not included).

func CountLines

func CountLines(rd io.Reader) (count int, err error)

CountLines counts all lines from the given reader (the line ending chars are not included).

func CreateHomeDir added in v0.1.9

func CreateHomeDir(dirs ...string) (string, error)

CreateHomeDir creates the nested directory inside home directory if passed in as arguments.

func CurrentFunctionName

func CurrentFunctionName() string

CurrentFunctionName returns name of current function.

func DateNowStr added in v0.0.15

func DateNowStr() string

DateNowStr returns the date of current local time. e.g. 2021-09-01

func DateUTCNowStr added in v0.0.15

func DateUTCNowStr() string

DateUTCNowStr returns the date of current UTC time. e.g. 2021-09-01

func DayBegin added in v0.0.15

func DayBegin(t time.Time, loc *time.Location) time.Time

DayBegin returns the first moment of the given time in given location.

func DayEnd added in v0.0.15

func DayEnd(t time.Time, loc *time.Location) time.Time

DayEnd returns the last moment of the given time in given location.

func Days added in v0.0.14

func Days(n float64) time.Duration

Days returns a duration of given days.

func DecodeBase36ToBytes

func DecodeBase36ToBytes(b string) []byte

DecodeBase36ToBytes decodes a base36 string to a byte slice, using alphabet.

func DelayRun added in v0.0.16

func DelayRun(interval time.Duration, task func()) context.CancelFunc

DelayRun waits for the duration to elapse and then calls task function, if it's not cancelled by the handler returns first. It's like time.AfterFunc but returns context.CancelFunc instead of time.Timer.

func DistinctInts added in v0.0.15

func DistinctInts(ori []int) []int

DistinctInts returns a new slice with the same order but without duplicate int elements.

func DurationPtr added in v0.2.3

func DurationPtr(d time.Duration) *time.Duration

DurationPtr returns a pointer to the time.Duration value passed in.

func DurationToString added in v0.1.4

func DurationToString(dr time.Duration) string

DurationToString returns a string representation (dd:HH:MM:SS.sss) of given duration.

func EmojiBool added in v0.1.5

func EmojiBool(yes bool) string

EmojiBool returns an emoji char representing the given boolean value.

func EmojiDone added in v0.1.5

func EmojiDone(done bool) string

EmojiDone returns an emoji char representing the given completion state.

func EncodeBytesAsBase36

func EncodeBytesAsBase36(b []byte) string

EncodeBytesAsBase36 encodes a byte slice to base36 string.

func EncodeBytesAsBase36Bytes

func EncodeBytesAsBase36Bytes(b []byte) []byte

EncodeBytesAsBase36Bytes encodes a byte slice to base36.

func EnsureRange added in v0.1.8

func EnsureRange(value, min, max int) int

EnsureRange returns the value if it's between min and max, otherwise it returns min or max, whichever is closer. It panics if min is greater than max.

func Eprint added in v0.2.2

func Eprint(a ...interface{}) (n int, err error)

Eprint likes fmt.Print but use stderr as the output.

func Eprintf added in v0.2.2

func Eprintf(format string, a ...interface{}) (n int, err error)

Eprintf likes fmt.Printf but use stderr as the output.

func Eprintln added in v0.2.2

func Eprintln(a ...interface{}) (n int, err error)

Eprintln likes fmt.Println but use stderr as the output.

func ErrorCause added in v0.2.3

func ErrorCause(err error) error

ErrorCause returns the cause of an error.

func ErrorPtr added in v0.2.3

func ErrorPtr(e error) *error

ErrorPtr returns a pointer to the error value passed in.

func ExtractBottomLines added in v0.1.5

func ExtractBottomLines(rd io.Reader, n int) ([]string, error)

ExtractBottomLines extracts the bottom n lines from the given stream (the line ending chars are not included), or lesser lines if the given stream doesn't contain enough line ending chars.

func ExtractFirstLine added in v0.1.5

func ExtractFirstLine(rd io.Reader) (string, error)

ExtractFirstLine extracts the first line from the given stream (the line ending chars are not included).

func ExtractLastLine added in v0.1.5

func ExtractLastLine(rd io.Reader) (string, error)

ExtractLastLine extracts the last line from the given stream (the line ending chars are not included).

func ExtractTopLines added in v0.1.5

func ExtractTopLines(rd io.Reader, n int) ([]string, error)

ExtractTopLines extracts the top n lines from the given stream (the line ending chars are not included), or lesser lines if the given stream doesn't contain enough line ending chars.

func FNV128a added in v0.1.2

func FNV128a(text string) []byte

FNV128a returns the 128-bit FNV-1a hash of the given string.

func FNV32a added in v0.1.2

func FNV32a(text string) uint32

FNV32a returns the 32-bit FNV-1a hash of the given string.

func FNV64a added in v0.1.2

func FNV64a(text string) uint64

FNV64a returns the 64-bit FNV-1a hash of the given string.

func FeelLucky

func FeelLucky(rate float64) bool

FeelLucky returns the random decision as per a given successful rate.

func FixedRetry

func FixedRetry(work func() error, times uint, delay time.Duration) error

FixedRetry retries to execute given function with consistent same delay.

func FixedRetryIf

func FixedRetryIf(work func() error, retryIf RetryIfFunc, times uint, delay time.Duration) error

FixedRetryIf retries to execute given function with consistent same delay if condition meets.

func Float32Ptr added in v0.2.3

func Float32Ptr(f float32) *float32

Float32Ptr returns a pointer to the float32 value passed in.

func Float64Ptr added in v0.2.3

func Float64Ptr(f float64) *float64

Float64Ptr returns a pointer to the float64 value passed in.

func FractionCeil

func FractionCeil(a, b int) int

FractionCeil returns the least integer value greater than or equal to a/b.

func FractionFloor

func FractionFloor(a, b int) int

FractionFloor returns the greatest integer value less than or equal to a/b.

func FractionFractional added in v0.0.15

func FractionFractional(a, b int) float64

FractionFractional returns the fractional part of floating-point number represented by a/b.

func FractionRound

func FractionRound(a, b int) int

FractionRound returns the nearest integer, rounding half away from zero of a/b.

func FractionTrunc

func FractionTrunc(a, b int) int

FractionTrunc returns the integer value of a/b.

func Fractional added in v0.1.1

func Fractional(f float64) float64

Fractional returns the fractional part of floating-point number f.

func Ftoa

func Ftoa(num float64) string

Ftoa converts a float to a string with no trailing zeros.

func FtoaWithDigits

func FtoaWithDigits(num float64, digits int) string

FtoaWithDigits converts a float to a string but limits the resulting string to the given number of decimal places, and no trailing zeros.

func FunctionName

func FunctionName(f interface{}) string

FunctionName returns name of the given function.

func GetCDKey added in v0.2.3

func GetCDKey() string

GetCDKey returns a new random CD key with 25 characters + 4 dashes in custom Base32 encoding (125 random bits in total), which contains no I, O, 0, 1.

func GetEnvVar

func GetEnvVar(key, fallback string) string

GetEnvVar returns the value of the given environment variable or the fallback.

func GetFingerprint

func GetFingerprint(s string) string

GetFingerprint returns SHA1 hash of a string in fingerprint format. e.g. 0a:4d:55:a8:d7:78:e5:02:2f:ab:70:19:77:c5:d8:40:bb:c4:86:d0

func GetHomeDir added in v0.1.9

func GetHomeDir(dirs ...string) (string, error)

GetHomeDir returns the home directory of the current user, or the nested directory inside home directory if passed in as arguments.

func GetSID

func GetSID() string

GetSID returns a new random UUID in base36 string. e.g. 3wqn6cl0uvfsbchw87izr8scm

func GetUB32 added in v0.1.10

func GetUB32() string

GetUB32 returns a new random UUID in standard base32 string without padding, i.e. 26-byte long. e.g. AMZIPGLFRVEQLKNI477QBST5V4

func GetUUID

func GetUUID() string

GetUUID returns a new random UUID in hex string. e.g. 7897af8b-9188-4fc5-9e0b-8bf63a2d7bab

func GetUnixTime

func GetUnixTime() int64

GetUnixTime returns a current time in unix timestamp.

func HereDoc added in v0.2.2

func HereDoc(raw string) string

HereDoc returns un-indented string as here-document.

func HereDocf added in v0.2.2

func HereDocf(raw string, args ...interface{}) string

HereDocf returns unindented and formatted string as here-document. Formatting is done as for fmt.Printf().

func Hours added in v0.0.14

func Hours(n float64) time.Duration

Hours returns a duration of given hours.

func HumanizeBytes

func HumanizeBytes(s uint64) string

HumanizeBytes produces a human readable representation of an SI size.

HumanizeBytes(82854982) -> 83 MB

func HumanizeDuration

func HumanizeDuration(duration time.Duration) string

HumanizeDuration humanizes time.Duration output to a meaningful value.

func HumanizeIBytes

func HumanizeIBytes(s uint64) string

HumanizeIBytes produces a human readable representation of an IEC size.

HumanizeIBytes(82854982) -> 79 MiB

func Int16Ptr added in v0.2.3

func Int16Ptr(i int16) *int16

Int16Ptr returns a pointer to the int16 value passed in.

func Int32Ptr added in v0.2.3

func Int32Ptr(i int32) *int32

Int32Ptr returns a pointer to the int32 value passed in.

func Int64Ptr added in v0.2.3

func Int64Ptr(i int64) *int64

Int64Ptr returns a pointer to the int64 value passed in.

func Int8Ptr added in v0.2.3

func Int8Ptr(i int8) *int8

Int8Ptr returns a pointer to the int8 value passed in.

func IntPtr added in v0.2.3

func IntPtr(i int) *int

IntPtr returns a pointer to the int value passed in.

func IntSlicePtr added in v0.2.3

func IntSlicePtr(s []int) *[]int

IntSlicePtr returns a pointer to the []int value passed in.

func InterfacePtr added in v0.2.3

func InterfacePtr(i interface{}) *interface{}

InterfacePtr returns a pointer to the interface value passed in.

func IsInterfaceNil added in v0.2.1

func IsInterfaceNil(i interface{}) bool

IsInterfaceNil returns true if the given interface is nil.

func IsNoNetworkError added in v0.2.1

func IsNoNetworkError(err error) bool

IsNoNetworkError indicates whether the error is caused by no network.

func IsSamePath added in v0.1.8

func IsSamePath(p1, p2 string) (bool, error)

IsSamePath returns true if two paths describe the same file.

func IsTextFile

func IsTextFile(path string) bool

IsTextFile loads and checks if the given path is a text file.

func IsTimeoutError added in v0.2.1

func IsTimeoutError(err error) bool

IsTimeoutError checks if error is timeout error.

func Itoa

func Itoa(i int) string

Itoa is equivalent to strconv.Itoa(i).

func Itoa16 added in v0.1.10

func Itoa16(i int16) string

Itoa16 is equivalent to strconv.FormatInt(int64(i), 10).

func Itoa32

func Itoa32(i int32) string

Itoa32 is equivalent to strconv.FormatInt(int64(i), 10).

func Itoa64

func Itoa64(i int64) string

Itoa64 is equivalent to strconv.FormatInt(i, 10).

func Itoa8 added in v0.1.10

func Itoa8(i int8) string

Itoa8 is equivalent to strconv.FormatInt(int64(i), 10).

func LastYear added in v0.2.3

func LastYear() int

LastYear returns the year of last year.

func LoadGobFile added in v0.1.8

func LoadGobFile(data interface{}, fileName string) error

LoadGobFile loads object from the given gob file.

func LoadJSONFile

func LoadJSONFile(data interface{}, fileName string) error

LoadJSONFile loads object from the given JSON file.

func LocalDayBegin added in v0.0.15

func LocalDayBegin(t time.Time) time.Time

LocalDayBegin returns the first moment of the given time in local timezone.

func LocalDayEnd added in v0.0.15

func LocalDayEnd(t time.Time) time.Time

LocalDayEnd returns the last moment of the given time in local timezone.

func MergeIntSequence added in v0.1.5

func MergeIntSequence(num []int, splitSep, rangeSep string) string

MergeIntSequence merges int slices like [8, 8, 9, 10, 20, 12]. into sequences like "8-10,12,20".

func MergeMaps

func MergeMaps(ms ...map[string]string) map[string]string

MergeMaps returns a new map as union set of given maps.

func Milliseconds added in v0.0.14

func Milliseconds(n float64) time.Duration

Milliseconds returns a duration of given milliseconds.

func Minutes added in v0.0.14

func Minutes(n float64) time.Duration

Minutes returns a duration of given minutes.

func MustParseDateString added in v0.1.4

func MustParseDateString(s string) time.Time

MustParseDateString returns a time.Time of given date string (format: 2006-01-02) in UTC, or panics if it fails.

func NewLocalDay added in v0.1.0

func NewLocalDay(year int, month time.Month, day int) time.Time

NewLocalDay returns the first moment of the given date in local timezone.

func NewUTCDay added in v0.1.0

func NewUTCDay(year int, month time.Month, day int) time.Time

NewUTCDay returns the first moment of the given date in UTC timezone.

func NextYear added in v0.2.3

func NextYear() int

NextYear returns the year of next year.

func NoopZapLogger

func NoopZapLogger() *zap.Logger

NoopZapLogger returns a zap logger enabled at fatal level, it basically logs nothing.

func NowStr added in v0.0.14

func NowStr() string

NowStr returns the current local time in RFC3339Nano format. e.g. 2021-09-01T12:52:33.250864+08:00

func ParallelTaskRun added in v0.1.9

func ParallelTaskRun(ctx context.Context, workerNum, taskNum int, runFunc TaskRunFunc, doneFunc TaskResultFunc) error

ParallelTaskRun runs a given number of tasks and handles results in parallel.

func ParseHumanizedBytes

func ParseHumanizedBytes(s string) (uint64, error)

ParseHumanizedBytes parses a string representation of bytes into the number of bytes it represents.

ParseHumanizedBytes("42 MB") -> 42000000, nil ParseHumanizedBytes("42 mib") -> 44040192, nil

func ParseIntSequence added in v0.0.15

func ParseIntSequence(s, splitSep, rangeSep string) ([]int, error)

ParseIntSequence parses sequences like "9-12,10,20" into slices of int like [9, 10, 11, 12, 20].

func ParseSI

func ParseSI(input string) (float64, string, error)

ParseSI parses an SI string back into the number and unit.

See also: SI, ComputeSI.

e.g. ParseSI("2.2345 pF") -> (2.2345e-12, "F", nil)

func ParseUnixTime

func ParseUnixTime(u int64) time.Time

ParseUnixTime converts a unix timestamp to local time.

func PercentageStr added in v0.1.2

func PercentageStr(a, b int) string

PercentageStr returns the percentage of a/b as a string.

func PostJSONAndDumps

func PostJSONAndDumps(url string, dataReq, dataResp interface{}, timeout time.Duration, headers map[string]string, dumpReqPath, dumpRespPath string) error

PostJSONAndDumps sends payload in JSON to target URL with given timeout and headers and dumps response and parses response as JSON.

func PostJSONWithHeaders

func PostJSONWithHeaders(url string, dataReq, dataResp interface{}, timeout time.Duration, headers map[string]string) error

PostJSONWithHeaders sends payload in JSON to target URL with given timeout and headers and parses response as JSON.

func PrintJSON

func PrintJSON(data interface{})

PrintJSON outputs data in JSON with indent to console.

func PrintOneLineJSON

func PrintOneLineJSON(data interface{})

PrintOneLineJSON outputs data in JSON in one line.

func Quote

func Quote() string

Quote returns the quote of current version.

func RandomDuration added in v0.0.16

func RandomDuration(min, max time.Duration) time.Duration

RandomDuration returns a random duration between [min, max).

func RandomFloat added in v0.1.5

func RandomFloat(min, max float64) float64

RandomFloat returns a random float64 number in [min, max).

func RandomInt added in v0.1.5

func RandomInt(min, max int) int

RandomInt returns a random int number in [min, max).

func RandomString added in v0.1.10

func RandomString(length int) string

RandomString returns a random string with given length, length should be greater than 0.

func RandomTime added in v0.0.16

func RandomTime(start time.Time, d time.Duration) time.Time

RandomTime returns a random time between [start, start+d) or [start+d, start) if d < 0.

func RandomTimeBetween added in v0.0.16

func RandomTimeBetween(start, end time.Time) time.Time

RandomTimeBetween returns a random time between [start, end).

func ReadByLine

func ReadByLine(rd io.Reader, callback LineFunc) (err error)

ReadByLine iterates the given Reader by lines (the line ending chars are not included).

func ReadFileByLine added in v0.1.0

func ReadFileByLine(path string, callback LineFunc) (err error)

ReadFileByLine iterates the given file by lines (the line ending chars are not included).

func ReadFileBytes added in v0.1.0

func ReadFileBytes(path string) ([]byte, error)

ReadFileBytes reads the whole named file and returns the contents. It's a sugar actually, simply calls os.ReadFile like ioutil.ReadFile does since Go 1.16.

func ReadFileLines added in v0.1.0

func ReadFileLines(path string) (lines []string, err error)

ReadFileLines reads all lines from the given file (the line ending chars are not included).

func ReadFileString added in v0.1.0

func ReadFileString(path string) (string, error)

ReadFileString reads the whole named file and returns the contents as a string.

func ReadLines

func ReadLines(rd io.Reader) (lines []string, err error)

ReadLines reads all lines from the given reader (the line ending chars are not included).

func ReadStdinPipe added in v0.1.1

func ReadStdinPipe() ([]byte, error)

ReadStdinPipe reads stdin data via pipe and returns the data.

func RegexMatch added in v0.0.15

func RegexMatch(pat, s string) (bool, error)

RegexMatch reports whether the string s contains any match of the regular expression pattern.

func RenderPartialBlock added in v0.2.1

func RenderPartialBlock(num float64, length int) string

RenderPartialBlock generates a partial block string like █▍░░ from a float64 between 0 and 1.

func RenderSparkline added in v0.1.6

func RenderSparkline(nums []float64) string

RenderSparkline generates a sparkline string like ▅▆▂▂▅▇▂▂▃▆▆▆▅▃ from a slice of float64.

func RenderTableString

func RenderTableString(header []string, rows [][]string) string

RenderTableString renders the rows as table and returns as string for console.

func ReplaceString added in v0.1.9

func ReplaceString(s string, opt ReplaceStringOptions) string

ReplaceString replaces all occurrences of given strings with replacements, with options to make all the replacements case-insensitive and imitate the case of old string.

func ReverseStr

func ReverseStr(s string) string

ReverseStr returns a reversed string of the given string.

func RoundToFixed added in v0.0.14

func RoundToFixed(num float64, precision int) float64

RoundToFixed returns the rounding floating number with given precision.

func RunCombinedCommand

func RunCombinedCommand(command string) ([]byte, error)

RunCombinedCommand runs the command and returns its combined standard output and standard error.

func RunQuietCommand

func RunQuietCommand(command string) error

RunQuietCommand runs the command quietly and returns no standard output nor standard error.

func RunSimpleCommand

func RunSimpleCommand(command string) ([]byte, []byte, error)

RunSimpleCommand simply runs the command and returns its standard output and standard error.

func RunWaitTimeout added in v0.0.16

func RunWaitTimeout(timeout time.Duration, task func() error) error

RunWaitTimeout calls the task function, and waits for the result for the given max timeout.

func RunePtr added in v0.2.3

func RunePtr(r rune) *rune

RunePtr returns a pointer to the rune value passed in.

func SI

func SI(input float64, unit string) string

SI returns a string with default formatting.

SI uses Ftoa to format float value, removing trailing zeros.

See also: ComputeSI, ParseSI.

e.g. SI(1000000, "B") -> 1 MB e.g. SI(2.2345e-12, "F") -> 2.2345 pF

func SIWithDigits

func SIWithDigits(input float64, decimals int, unit string) string

SIWithDigits works like SI but limits the resulting string to the given number of decimal places.

e.g. SIWithDigits(1000000, 0, "B") -> 1 MB e.g. SIWithDigits(2.2345e-12, 2, "F") -> 2.23 pF

func SaveGobFile added in v0.1.8

func SaveGobFile(data interface{}, fileName string) error

SaveGobFile saves object as a gob file.

func SaveJSONFile

func SaveJSONFile(data interface{}, fileName string) error

SaveJSONFile saves object as a JSON file.

func Seconds added in v0.0.14

func Seconds(n float64) time.Duration

Seconds returns a duration of given seconds.

func ShortFunctionName

func ShortFunctionName(f interface{}) string

ShortFunctionName returns short name of the given function.

func ShortNowStr added in v0.0.14

func ShortNowStr() string

ShortNowStr returns the current local time in short format. e.g. 2021-09-01 12:52:33

func ShortUTCNowStr added in v0.0.15

func ShortUTCNowStr() string

ShortUTCNowStr returns the current UTC time in short format. e.g. 2021-09-01 04:52:33

func SimpleRetry

func SimpleRetry(work func() error) error

SimpleRetry retries to execute given function for 3 times and with exponential backoff delay starting at 300ms.

func SimpleZapLogger

func SimpleZapLogger() *zap.Logger

SimpleZapLogger returns a zap logger with color console as output.

func SimpleZapSugaredLogger

func SimpleZapSugaredLogger() *zap.SugaredLogger

SimpleZapSugaredLogger returns a sugared zap logger with color console as output.

func SleepForDays added in v0.0.14

func SleepForDays(n float64)

SleepForDays pauses the current goroutine for at least the n days.

func SleepForHours added in v0.0.14

func SleepForHours(n float64)

SleepForHours pauses the current goroutine for at least the n hours.

func SleepForMilliseconds added in v0.0.14

func SleepForMilliseconds(n float64)

SleepForMilliseconds pauses the current goroutine for at least the n milliseconds.

func SleepForMinutes added in v0.0.14

func SleepForMinutes(n float64)

SleepForMinutes pauses the current goroutine for at least the n minutes.

func SleepForSeconds added in v0.0.14

func SleepForSeconds(n float64)

SleepForSeconds pauses the current goroutine for at least the n seconds.

func SleepWithContext added in v0.0.16

func SleepWithContext(ctx context.Context, d time.Duration) error

SleepWithContext pauses the current goroutine for the duration d or shorter duration if the context is cancelled. A negative or zero duration causes SleepWithContext to return immediately.

func StringPtr added in v0.2.3

func StringPtr(s string) *string

StringPtr returns a pointer to the string value passed in.

func StringSlicePtr added in v0.2.3

func StringSlicePtr(s []string) *[]string

StringSlicePtr returns a pointer to the []string value passed in.

func StyleBold

func StyleBold(val string) string

StyleBold renders a string in bold.

func StyleCrossOut

func StyleCrossOut(val string) string

StyleCrossOut renders a string with cross-out.

func StyleEmail

func StyleEmail(email string) string

StyleEmail renders a string of email with terminal colors.

func StyleLabeledLineBreak added in v0.2.1

func StyleLabeledLineBreak(label string) string

StyleLabeledLineBreak renders a line break with a label in the middle.

func SubstrAfterFirst

func SubstrAfterFirst(s, sub string) string

SubstrAfterFirst returns a substring which starts after the first occurrence of target and continues to the end, or empty string if the target is not found or empty.

func SubstrAfterLast

func SubstrAfterLast(s, sub string) string

SubstrAfterLast returns a substring which starts after the last occurrence of target and continues to the end, or empty string if the target is not found or empty.

func SubstrBeforeFirst

func SubstrBeforeFirst(s, sub string) string

SubstrBeforeFirst returns a substring which starts starts at the begin of a string and continues to the first occurrence of target, or empty string if the target is not found or empty.

func SubstrBeforeLast

func SubstrBeforeLast(s, sub string) string

SubstrBeforeLast returns a substring which starts starts at the begin of a string and continues to the last occurrence of target, or empty string if the target is not found or empty.

func SubstrOrOrigin

func SubstrOrOrigin(subFunc func(string, string) string, s, sub string) string

SubstrOrOrigin returns the original string if the target is missed in substr function.

func ThisYear added in v0.2.3

func ThisYear() int

ThisYear returns the year of current date.

func TimePtr added in v0.2.3

func TimePtr(t time.Time) *time.Time

TimePtr returns a pointer to the time.Time value passed in.

func ToJSON

func ToJSON(data interface{}) string

ToJSON returns JSON string of data with indent.

func ToOneLineJSON added in v0.2.0

func ToOneLineJSON(data interface{}) string

ToOneLineJSON returns JSON string of data in one line.

func TrimInnerSpace added in v0.1.10

func TrimInnerSpace(s string) string

TrimInnerSpace returns a string with all inner, leading, trailing spaces removed.

func TrimLeftSpace added in v0.1.8

func TrimLeftSpace(s string) string

TrimLeftSpace returns a string with all leading spaces removed.

func TrimRightSpace added in v0.1.8

func TrimRightSpace(s string) string

TrimRightSpace returns a string with all trailing spaces removed.

func TrimUTF8BOM

func TrimUTF8BOM(b []byte) []byte

TrimUTF8BOM removes the leading UTF-8 byte order mark from bytes.

func TruncateStr

func TruncateStr(s string, limit int) string

TruncateStr renders a truncated string of the given length, or original one if it's shorter.

func UTCDayBegin added in v0.0.15

func UTCDayBegin(t time.Time) time.Time

UTCDayBegin returns the first moment of the given time in UTC timezone.

func UTCDayEnd added in v0.0.15

func UTCDayEnd(t time.Time) time.Time

UTCDayEnd returns the last moment of the given time in UTC timezone.

func UTCNow added in v0.0.14

func UTCNow() time.Time

UTCNow returns the current UTC time.

func UTCNowStr added in v0.0.14

func UTCNowStr() string

UTCNowStr returns the current UTC time in RFC3339Nano format. e.g. 2021-09-01T04:52:33.251188Z

func Uint16Ptr added in v0.2.3

func Uint16Ptr(u uint16) *uint16

Uint16Ptr returns a pointer to the uint16 value passed in.

func Uint32Ptr added in v0.2.3

func Uint32Ptr(u uint32) *uint32

Uint32Ptr returns a pointer to the uint32 value passed in.

func Uint64Ptr added in v0.2.3

func Uint64Ptr(u uint64) *uint64

Uint64Ptr returns a pointer to the uint64 value passed in.

func Uint8Ptr added in v0.2.3

func Uint8Ptr(u uint8) *uint8

Uint8Ptr returns a pointer to the uint8 value passed in.

func UintPtr added in v0.2.3

func UintPtr(u uint) *uint

UintPtr returns a pointer to the uint value passed in.

func UintptrPtr added in v0.2.3

func UintptrPtr(u uintptr) *uintptr

UintptrPtr returns a pointer to the uintptr value passed in.

func UnzipDir

func UnzipDir(srcZip, destDir string, opts ...UnzipConflictStrategy) ([]string, error)

UnzipDir decompresses a zip archive, extracts all files and folders within the zip file to an output directory.

func UnzipFile

func UnzipFile(srcZip string, handle func(file *zip.File) error) error

UnzipFile decompresses a zip archive, extracts all files and call handlers.

func UpdateMinMaxFloat64 added in v0.1.8

func UpdateMinMaxFloat64(value float64, min, max *float64)

UpdateMinMaxFloat64 updates the min and max values if the value is less than the current min or greater than the current max.

The function takes three arguments:

* value: The value to compare against the current min and max. * min: A pointer to the current min value. * max: A pointer to the current max value.

func UpdateMinMaxInt added in v0.1.8

func UpdateMinMaxInt(value int, min, max *int)

UpdateMinMaxInt updates the min and max values if the value is less than the current min or greater than the current max.

The function takes three arguments:

* value: The value to compare against the current min and max. * min: A pointer to the current min value. * max: A pointer to the current max value.

func Utoa

func Utoa(i uint) string

Utoa is equivalent to strconv.FormatUint(uint64(i), 10).

func Utoa16 added in v0.1.10

func Utoa16(i uint16) string

Utoa16 is equivalent to strconv.FormatUint(uint64(i), 10).

func Utoa32

func Utoa32(i uint32) string

Utoa32 is equivalent to strconv.FormatUint(uint64(i), 10).

func Utoa64

func Utoa64(i uint64) string

Utoa64 is equivalent to strconv.FormatUint(i, 10).

func Utoa8 added in v0.1.10

func Utoa8(i uint8) string

Utoa8 is equivalent to strconv.FormatUint(uint64(i), 10).

func Weeks added in v0.0.14

func Weeks(n float64) time.Duration

Weeks returns a duration of given weeks.

func WriteFileBytes added in v0.1.0

func WriteFileBytes(path string, data []byte) error

WriteFileBytes writes the given data into a file.

func WriteFileLines added in v0.1.0

func WriteFileLines(path string, lines []string) error

WriteFileLines writes the given lines as a text file.

func WriteFileString added in v0.1.0

func WriteFileString(path string, content string) error

WriteFileString writes the given content string into a file.

func WriteLines

func WriteLines(wr io.Writer, lines []string) error

WriteLines writes the given lines to a Writer.

func Years added in v0.0.14

func Years(n float64) time.Duration

Years returns a duration of given years.

func ZipContent

func ZipContent(destZip string, content ArchiveContent) error

ZipContent compresses data entries into a single zip archive file.

func ZipDir

func ZipDir(destZip string, srcDirs ...string) error

ZipDir compresses one or many directories into a single zip archive file. Existing destination file will be overwritten.

func ZipFile

func ZipFile(destZip string, srcFiles ...string) error

ZipFile compresses one or many files into a single zip archive file.

Types

type ArchiveContent

type ArchiveContent map[string][]byte

ArchiveContent represents a map between filename and data.

func UnzipContent

func UnzipContent(srcZip string) (ArchiveContent, error)

UnzipContent decompresses a zip archive, extracts all files within the zip file to map of bytes.

type Command

type Command struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Command represents an external command being running or exited.

func StartCommand

func StartCommand(command string, opts ...*CommandOptions) (*Command, error)

StartCommand starts the specified command with given options but does not wait for it to complete.

func StartSimpleCommand

func StartSimpleCommand(command string, writerStdout, writerStderr io.Writer) (*Command, error)

StartSimpleCommand starts the specified command but does not wait for it to complete, and simultaneously writes its standard output and standard error to given writers.

func (*Command) Done

func (c *Command) Done() <-chan struct{}

Done returns a channel that's closed when the command exits.

func (*Command) Error

func (c *Command) Error() error

Error returns the error after the command exits if it exists.

func (*Command) Exited

func (c *Command) Exited() bool

Exited reports whether the command has exited.

func (*Command) Kill

func (c *Command) Kill() error

Kill causes the command to exit immediately, and does not wait until it has actually exited.

func (*Command) ProcessID

func (c *Command) ProcessID() int

ProcessID indicates PID of the command.

func (*Command) StartedAt

func (c *Command) StartedAt() time.Time

StartedAt indicates the moment that the command started.

func (*Command) Stderr

func (c *Command) Stderr() []byte

Stderr returns a slice holding the content of the standard error of the command.

func (*Command) Stdout

func (c *Command) Stdout() []byte

Stdout returns a slice holding the content of the standard output of the command.

func (*Command) StoppedAt

func (c *Command) StoppedAt() time.Time

StoppedAt indicates the moment that the command stopped or zero if it's still running.

type CommandOptions

type CommandOptions struct {
	// WorkDir is the working directory of the command.
	WorkDir string
	// EnvVar appends the environment variables of the command.
	EnvVar map[string]string
	// Stdout is the writer to write standard output to. Use os.Pipe() to create a pipe for this, if you want to handle the result synchronously.
	Stdout io.Writer
	// Stderr is the writer to write standard error to. Use os.Pipe() to create a pipe for this, if you want to handle the result synchronously.
	Stderr io.Writer
	// DisableResult indicates whether to disable the buffered result of the command, especially important for long-running commands.
	DisableResult bool
	// Stdin is the input to the command's standard input.
	Stdin io.Reader
	// TODO: not implemented
	Timeout time.Time
}

CommandOptions represents custom options to execute external command.

type Date added in v0.1.0

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

Date represents the missing data structure for date.

func FirstDayOfMonth added in v0.1.1

func FirstDayOfMonth() Date

FirstDayOfMonth returns the first day of current month.

func FirstDayOfYear added in v0.1.1

func FirstDayOfYear() Date

FirstDayOfYear returns the first day of current year.

func LastDayOfMonth added in v0.1.1

func LastDayOfMonth() Date

LastDayOfMonth returns the last day of current month.

func LastDayOfYear added in v0.1.1

func LastDayOfYear() Date

LastDayOfYear returns the last day of current year.

func NewDate added in v0.1.0

func NewDate(year, month, day int) Date

NewDate creates a new Date instance.

func NewDateFromTime added in v0.1.0

func NewDateFromTime(t time.Time) Date

NewDateFromTime converts a time.Time into Date instance.

func ParseDate added in v0.1.0

func ParseDate(s string) (*Date, error)

ParseDate parses a formatted string into Date structure.

func Today added in v0.1.1

func Today() Date

Today returns the current date.

func Tomorrow added in v0.2.3

func Tomorrow() Date

Tomorrow returns the date of tomorrow.

func UTCToday added in v0.1.1

func UTCToday() Date

UTCToday returns the current date in UTC.

func UTCTomorrow added in v0.2.3

func UTCTomorrow() Date

UTCTomorrow returns the date of tomorrow in UTC.

func UTCYesterday added in v0.2.3

func UTCYesterday() Date

UTCYesterday returns the date of yesterday in UTC.

func Yesterday added in v0.2.3

func Yesterday() Date

Yesterday returns the date of yesterday.

func (Date) Add added in v0.1.0

func (d Date) Add(t time.Duration) Date

Add returns a Date instance for the duration after the given date.

func (Date) AddDay added in v0.1.0

func (d Date) AddDay(n int) Date

AddDay returns a Date instance for given days after the current date.

func (Date) AddMonth added in v0.1.0

func (d Date) AddMonth(n int) Date

AddMonth returns a Date instance for given months after the current date.

func (Date) AddYear added in v0.1.0

func (d Date) AddYear(n int) Date

AddYear returns a Date instance for given years after the current date.

func (Date) After added in v0.1.0

func (d Date) After(t Date) bool

After indicates if current date is later than the given date.

func (Date) Before added in v0.1.0

func (d Date) Before(t Date) bool

Before indicates if current date is earlier than the given date.

func (*Date) Clone added in v0.2.2

func (d *Date) Clone() Date

Clone returns a copy of current instance.

func (Date) Day added in v0.1.0

func (d Date) Day() int

Day returns the day of the month specified by d.

func (Date) Equal added in v0.1.0

func (d Date) Equal(t Date) bool

Equal indicates if current date and the given date are equal.

func (Date) IsSameDay added in v0.2.2

func (d Date) IsSameDay(t Date) bool

IsSameDay returns true if current date and the given date are in the same day of the same month of the same year.

func (Date) IsSameMonth added in v0.2.2

func (d Date) IsSameMonth(t Date) bool

IsSameMonth returns true if current date and the given date are in the same month of the same year.

func (Date) IsSameYear added in v0.2.2

func (d Date) IsSameYear(t Date) bool

IsSameYear returns true if current date and the given date are in the same year.

func (Date) IsZero added in v0.2.2

func (d Date) IsZero() bool

IsZero indicates if current date is zero value.

func (Date) LocalTime added in v0.1.0

func (d Date) LocalTime() time.Time

LocalTime returns a local time.Time for current instance.

func (Date) MarshalJSON added in v0.1.0

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. The time is a quoted string in ISO 8601 date format, with sub-second precision added if present.

func (Date) MarshalText added in v0.1.0

func (d Date) MarshalText() (text []byte, err error)

MarshalText implements the encoding.TextMarshaler interface. The time is formatted in ISO 8601 date format, with sub-second precision added if present.

func (Date) Month added in v0.1.0

func (d Date) Month() time.Month

Month returns the month of the year specified by d.

func (Date) String added in v0.1.0

func (d Date) String() string

func (Date) Sub added in v0.1.2

func (d Date) Sub(t Date) time.Duration

Sub returns the duration between two dates.

func (Date) SubInDay added in v0.1.2

func (d Date) SubInDay(t Date) int

SubInDay returns the duration between two dates in day.

func (Date) Time added in v0.1.0

func (d Date) Time(loc *time.Location) time.Time

Time returns a time.Time with given location for current instance.

func (Date) UTCTime added in v0.1.0

func (d Date) UTCTime() time.Time

UTCTime returns a UTC time.Time for current instance.

func (*Date) UnmarshalJSON added in v0.1.0

func (d *Date) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. The date is expected to be a quoted string in ISO 8601 date format.

func (*Date) UnmarshalText added in v0.1.0

func (d *Date) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be in ISO 8601 date format.

func (Date) Year added in v0.1.0

func (d Date) Year() int

Year returns the year in which d occurs.

type HTTPClient added in v0.2.1

type HTTPClient struct {
	*http.Client
	// contains filtered or unexported fields
}

HTTPClient is a wrapper of http.Client with some helper methods.

func NewHTTPClient added in v0.2.1

func NewHTTPClient(opts *HTTPClientOptions) *HTTPClient

NewHTTPClient creates a new HTTPClient.

func (*HTTPClient) Custom added in v0.2.1

func (c *HTTPClient) Custom(method, url string, queryArgs, headers map[string]string, payload io.Reader) ([]byte, error)

Custom performs a custom request with given method, url, query arguments, headers and io.Reader payload as body.

func (*HTTPClient) Get added in v0.2.1

func (c *HTTPClient) Get(url string, queryArgs, headers map[string]string) ([]byte, error)

Get performs a GET request. It shadows the http.Client.Get method.

func (*HTTPClient) GetJSON added in v0.2.1

func (c *HTTPClient) GetJSON(url string, queryArgs, headers map[string]string, result interface{}) ([]byte, error)

GetJSON performs a GET request, parses the JSON-encoded response data and stores in the value pointed to by result.

func (*HTTPClient) Post added in v0.2.1

func (c *HTTPClient) Post(url string, queryArgs, headers map[string]string, payload io.Reader) ([]byte, error)

Post performs a POST request with given io.Reader payload as body. It shadows the http.Client.Post method.

func (*HTTPClient) PostData added in v0.2.1

func (c *HTTPClient) PostData(url string, queryArgs, headers map[string]string, payload []byte) ([]byte, error)

PostData performs a POST request with given bytes payload as body.

func (*HTTPClient) PostForm added in v0.2.3

func (c *HTTPClient) PostForm(url string, queryArgs, headers map[string]string, form url.Values) ([]byte, error)

PostForm performs a POST request with given form data as body.

func (*HTTPClient) PostJSON added in v0.2.1

func (c *HTTPClient) PostJSON(url string, queryArgs, headers map[string]string, payload, result interface{}) ([]byte, error)

PostJSON performs a POST request with given JSON payload as body, parses the JSON-encoded response data and stores in the value pointed to by result.

type HTTPClientOptions added in v0.2.1

type HTTPClientOptions struct {
	// Client is the underlying http.Client, you can set it to use your own client with transport.
	Client *http.Client
	// Timeout is the maximum amount of time a dial will wait for a connect to complete.
	Timeout time.Duration
	// UserAgent is the User-Agent header value.
	UserAgent string
	// Headers is the default HTTP headers.
	Headers map[string]string
	// Insecure indicates whether to skip TLS verification.
	Insecure bool
	// DisableRedirect indicates whether to disable redirect for HTTP 301, 302, 303, 307, 308.
	DisableRedirect bool
	// Username is the username for basic authentication.
	Username string
	// Password is the password for basic authentication.
	Password string
	// BearerToken is the bearer token for token authentication. It will override the basic authentication if it's set together.
	BearerToken string
}

HTTPClientOptions represents options for HTTPClient.

type LineFunc

type LineFunc func(line string) (err error)

LineFunc stands for a handler for each line string.

type LogConfig

type LogConfig struct {
	ConsoleFormat string
	FileFormat    string
	Monochrome    bool
	MaxFileSizeMB int
	MaxBackups    int
	CompressFile  bool
}

LogConfig stands for config of logging.

type Logger

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

Logger is a wrapper of uber/zap logger with dynamic log level.

func NewJSONLogger

func NewJSONLogger(fileName string, debug bool) *Logger

NewJSONLogger returns a Logger with given log path and debug mode and all output format is JSON.

func NewLogger

func NewLogger(fileName string, debug bool, cfgs ...LogConfig) *Logger

NewLogger returns a Logger with given log path and debug mode.

func NewMonochromeLogger added in v0.1.2

func NewMonochromeLogger(fileName string, debug bool) *Logger

NewMonochromeLogger returns a Logger with given log path and debug mode and output in console, save as json, and never cleans up.

func NewPersistentLogger

func NewPersistentLogger(fileName string, debug bool) *Logger

NewPersistentLogger returns a Logger with given log path and debug mode and output in console with color, save as json, and never cleans up.

func (*Logger) GetLogLevel

func (l *Logger) GetLogLevel() zapcore.Level

GetLogLevel returns the log level of loggers inside the wrapper.

func (*Logger) Logger

func (l *Logger) Logger() *zap.Logger

Logger returns a zap logger inside the wrapper.

func (*Logger) LoggerSugared

func (l *Logger) LoggerSugared() *zap.SugaredLogger

LoggerSugared returns a sugared zap logger inside the wrapper.

func (*Logger) SetLogLevel

func (l *Logger) SetLogLevel(level string)

SetLogLevel sets the log level of loggers inside the wrapper.

type NamedValues

type NamedValues map[string]string

NamedValues represents a named value map for named capturing groups.

func ExtractNamedValues

func ExtractNamedValues(r *regexp.Regexp, str string) NamedValues

ExtractNamedValues returns a named value map with the given compiled regular expression and original string.

func (NamedValues) IsEmpty

func (l NamedValues) IsEmpty() bool

IsEmpty indicates if the given map is empty.

type ReplaceStringOptions added in v0.1.9

type ReplaceStringOptions struct {
	// Replacements is a map of old-new string pairs.
	Replacements map[string]string
	// CaseInsensitive indicates if the match should be case-insensitive.
	CaseInsensitive bool
	// ImitateResult indicates if the result should be the imitation (about case) of the original string.
	ImitateResult bool
}

ReplaceStringOptions indicates the options for the ReplaceString function.

type RetryIfFunc

type RetryIfFunc func(error) bool

RetryIfFunc represents function signature of retry if function.

type Stopwatch

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

Stopwatch provides a set of methods to measure elapsed time.

func NewStopwatch

func NewStopwatch() *Stopwatch

NewStopwatch returns a Stopwatch instance which just starts to measure.

func (*Stopwatch) Elapsed

func (sw *Stopwatch) Elapsed() time.Duration

Elapsed returns the total elapsed time measured by the current instance.

func (*Stopwatch) ElapsedMilliseconds added in v0.0.16

func (sw *Stopwatch) ElapsedMilliseconds() int64

ElapsedMilliseconds returns the total elapsed time measured by the current instance, in milliseconds.

func (*Stopwatch) Show

func (sw *Stopwatch) Show()

Show outputs elapsed time measured by the current instance to console.

type TaskResultFunc added in v0.1.9

type TaskResultFunc func(ctx context.Context, taskID int, result interface{}, err error)

TaskResultFunc is a function that handles the result of a task.

type TaskRunFunc added in v0.1.9

type TaskRunFunc func(ctx context.Context, taskID int) (interface{}, error)

TaskRunFunc is a function that runs a task and returns the result with error.

type UnzipConflictStrategy added in v0.2.1

type UnzipConflictStrategy uint8

UnzipConflictStrategy defines the strategy to handle the conflict when extracting files from a zip archive.

const (
	// UnzipConflictSkip skips the file if it already exists in the destination folder.
	UnzipConflictSkip UnzipConflictStrategy = iota
	// UnzipConflictOverwrite overwrites the file if it already exists in the destination folder.
	UnzipConflictOverwrite
	// UnzipConflictRename renames the new file if it already exists in the destination folder.
	UnzipConflictRename
	// UnzipConflictKeepOld keeps the file with earlier modification time if it already exists in the destination folder.
	UnzipConflictKeepOld
	// UnzipConflictKeepNew keeps the file with later modification time if it already exists in the destination folder.
	UnzipConflictKeepNew
)

Jump to

Keyboard shortcuts

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