Documentation ¶
Index ¶
- Constants
- Variables
- func AccumulatedChannel(inCh <-chan []byte, size int) <-chan []byte
- func AfterNow(t time.Time) bool
- func AppStartTime() time.Time
- func AppUpTime() time.Duration
- func AppendFileBytes(path string, data []byte) error
- func AppendFileLines(path string, lines []string) error
- func AppendFileString(path string, content string) error
- func Atoi(s string) (int, error)
- func Atoi32(s string) (int32, error)
- func Atoi64(s string) (int64, error)
- func Atou(s string) (uint, error)
- func Atou32(s string) (uint32, error)
- func Atou64(s string) (uint64, error)
- func BackOffRetry(work func() error, times uint, delay time.Duration) error
- func BackOffRetryIf(work func() error, retryIf RetryIfFunc, times uint, delay time.Duration) error
- func BeforeNow(t time.Time) bool
- func BlockForever()
- func ChangeDir(path string)
- func CharBool(yes bool) string
- func ChooseWeightStrMap(weightMap map[string]float64) string
- func ComputeSI(input float64) (float64, string)
- func ContainsChinese(s string) bool
- func ContainsJapanese(s string) bool
- func ContainsKorean(s string) bool
- func CountDigit(num int) int
- func CountFileLines(path string) (count int, err error)
- func CountLines(rd io.Reader) (count int, err error)
- func CurrentFunctionName() string
- func DateNowStr() string
- func DateUTCNowStr() string
- func DayBegin(t time.Time, loc *time.Location) time.Time
- func DayEnd(t time.Time, loc *time.Location) time.Time
- func Days(n float64) time.Duration
- func DecodeBase36ToBytes(b string) []byte
- func DelayRun(interval time.Duration, task func()) context.CancelFunc
- func DistinctInts(ori []int) []int
- func DurationToString(d time.Duration) string
- func EmojiBool(yes bool) string
- func EmojiDone(done bool) string
- func EncodeBytesAsBase36(b []byte) string
- func EncodeBytesAsBase36Bytes(b []byte) []byte
- func ExtractBottomLines(rd io.Reader, n int) ([]string, error)
- func ExtractFirstLine(rd io.Reader) (string, error)
- func ExtractLastLine(rd io.Reader) (string, error)
- func ExtractTopLines(rd io.Reader, n int) ([]string, error)
- func FNV128a(text string) []byte
- func FNV32a(text string) uint32
- func FNV64a(text string) uint64
- func FeelLucky(rate float64) bool
- func FixedRetry(work func() error, times uint, delay time.Duration) error
- func FixedRetryIf(work func() error, retryIf RetryIfFunc, times uint, delay time.Duration) error
- func FractionCeil(a, b int) int
- func FractionFloor(a, b int) int
- func FractionFractional(a, b int) float64
- func FractionRound(a, b int) int
- func FractionTrunc(a, b int) int
- func Fractional(f float64) float64
- func Ftoa(num float64) string
- func FtoaWithDigits(num float64, digits int) string
- func FunctionName(f interface{}) string
- func GenerateRSAKeys(bitSize int) (pubKey string, privKey string, err error)
- func GetEnvVar(key, fallback string) string
- func GetFingerprint(s string) string
- func GetSID() string
- func GetUUID() string
- func GetUnixTime() int64
- func Hours(n float64) time.Duration
- func HumanizeBytes(s uint64) string
- func HumanizeDuration(duration time.Duration) string
- func HumanizeIBytes(s uint64) string
- func IsTextFile(path string) bool
- func Itoa(i int) string
- func Itoa32(i int32) string
- func Itoa64(i int64) string
- func LoadJSONFile(s interface{}, fileName string) error
- func LocalDayBegin(t time.Time) time.Time
- func LocalDayEnd(t time.Time) time.Time
- func MergeIntSequence(num []int, splitSep, rangeSep string) string
- func MergeMaps(ms ...map[string]string) map[string]string
- func Milliseconds(n float64) time.Duration
- func Minutes(n float64) time.Duration
- func MustParseDateString(s string) time.Time
- func NewLocalDay(year int, month time.Month, day int) time.Time
- func NewUTCDay(year int, month time.Month, day int) time.Time
- func NoopZapLogger() *zap.Logger
- func NowStr() string
- func ParseHumanizedBytes(s string) (uint64, error)
- func ParseIntSequence(s, splitSep, rangeSep string) ([]int, error)
- func ParseSI(input string) (float64, string, error)
- func ParseUnixTime(u int64) time.Time
- func PercentageStr(a, b int) string
- func PostJSONAndDumps(url string, dataReq, dataResp interface{}, timeout time.Duration, ...) error
- func PostJSONWithHeaders(url string, dataReq, dataResp interface{}, timeout time.Duration, ...) error
- func PrintColorfulJSON(data interface{})
- func PrintJSON(data interface{})
- func PrintOneLineJSON(data interface{})
- func Quote() string
- func RandomDuration(min, max time.Duration) time.Duration
- func RandomFloat(min, max float64) float64
- func RandomInt(min, max int) int
- func RandomTime(start time.Time, d time.Duration) time.Time
- func RandomTimeBetween(start, end time.Time) time.Time
- func ReadByLine(rd io.Reader, callback LineFunc) (err error)
- func ReadFileByLine(path string, callback LineFunc) (err error)
- func ReadFileBytes(path string) ([]byte, error)
- func ReadFileLines(path string) (lines []string, err error)
- func ReadFileString(path string) (string, error)
- func ReadLines(rd io.Reader) (lines []string, err error)
- func ReadStdinPipe() ([]byte, error)
- func RegexMatch(pat, s string) (bool, error)
- func RenderSparkline(nums []float64) string
- func RenderTableString(header []string, rows [][]string) string
- func ReverseStr(s string) string
- func RoundToFixed(num float64, precision int) float64
- func RunCombinedCommand(command string) ([]byte, error)
- func RunQuietCommand(command string) error
- func RunSimpleCommand(command string) ([]byte, []byte, error)
- func RunWaitTimeout(timeout time.Duration, task func() error) error
- func SI(input float64, unit string) string
- func SIWithDigits(input float64, decimals int, unit string) string
- func SaveJSONFile(data interface{}, fileName string) error
- func Seconds(n float64) time.Duration
- func ShortFunctionName(f interface{}) string
- func ShortNowStr() string
- func ShortUTCNowStr() string
- func SimpleRetry(work func() error) error
- func SimpleZapLogger() *zap.Logger
- func SimpleZapSugaredLogger() *zap.SugaredLogger
- func SleepForDays(n float64)
- func SleepForHours(n float64)
- func SleepForMilliseconds(n float64)
- func SleepForMinutes(n float64)
- func SleepForSeconds(n float64)
- func SleepWithContext(ctx context.Context, d time.Duration) error
- func StyleBold(val string) string
- func StyleCrossOut(val string) string
- func StyleEmail(email string) string
- func SubstrAfterFirst(s, sub string) string
- func SubstrAfterLast(s, sub string) string
- func SubstrBeforeFirst(s, sub string) string
- func SubstrBeforeLast(s, sub string) string
- func SubstrOrOrigin(subFunc func(string, string) string, s, sub string) string
- func ToJSON(data interface{}) string
- func TrimUTF8BOM(b []byte) []byte
- func TruncateStr(s string, limit int) string
- func UTCDayBegin(t time.Time) time.Time
- func UTCDayEnd(t time.Time) time.Time
- func UTCNow() time.Time
- func UTCNowStr() string
- func UnzipDir(srcZip string, destDir string) ([]string, error)
- func UnzipFile(srcZip string, handle func(file *zip.File) error) error
- func Utoa(i uint) string
- func Utoa32(i uint32) string
- func Utoa64(i uint64) string
- func Weeks(n float64) time.Duration
- func WriteFileBytes(path string, data []byte) error
- func WriteFileLines(path string, lines []string) error
- func WriteFileString(path string, content string) error
- func WriteLines(wr io.Writer, lines []string) error
- func Years(n float64) time.Duration
- func ZipContent(destZip string, content ArchiveContent) error
- func ZipDir(destZip string, srcDirs ...string) error
- func ZipFile(destZip string, srcFiles ...string) error
- type ArchiveContent
- type Command
- func (c *Command) Done() <-chan struct{}
- func (c *Command) Error() error
- func (c *Command) Exited() bool
- func (c *Command) Kill() error
- func (c *Command) ProcessID() int
- func (c *Command) StartedAt() time.Time
- func (c *Command) Stderr() []byte
- func (c *Command) Stdout() []byte
- func (c *Command) StoppedAt() time.Time
- type CommandOptions
- type Date
- func (d Date) Add(t time.Duration) Date
- func (d Date) AddDay(n int) Date
- func (d Date) AddMonth(n int) Date
- func (d Date) AddYear(n int) Date
- func (d Date) After(t Date) bool
- func (d Date) Before(t Date) bool
- func (d Date) Day() int
- func (d Date) Equal(t Date) bool
- func (d Date) LocalTime() time.Time
- func (d Date) MarshalJSON() ([]byte, error)
- func (d Date) MarshalText() (text []byte, err error)
- func (d Date) Month() time.Month
- func (d Date) String() string
- func (d Date) Sub(t Date) time.Duration
- func (d Date) SubInDay(t Date) int
- func (d Date) Time(loc *time.Location) time.Time
- func (d Date) UTCTime() time.Time
- func (d *Date) UnmarshalJSON(data []byte) error
- func (d *Date) UnmarshalText(text []byte) error
- func (d Date) Year() int
- type LineFunc
- type LogConfig
- type Logger
- type NamedValues
- type RetryIfFunc
- type Stopwatch
Constants ¶
const ( Byte = 1 << (iota * 10) KiByte MiByte GiByte TiByte PiByte EiByte )
IEC Sizes. kibis of bits
const ( IByte = 1 KByte = IByte * 1000 MByte = KByte * 1000 GByte = MByte * 1000 TByte = GByte * 1000 PByte = TByte * 1000 EByte = PByte * 1000 )
SI Sizes.
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) )
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 ¶
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} )
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") )
var ( // ZeroDuration is a zero-value for time.Duration. ZeroDuration time.Duration // ZeroTime is a zero-value for time.Time. ZeroTime = time.Time{} )
var DiscardWriteCloser io.WriteCloser = discardCloser{}
DiscardWriteCloser is a WriteCloser on which all Write calls succeed without doing anything.
var DiscardWriter = io.Discard
DiscardWriter is a Writer on which all Write calls succeed without doing anything.
var EmptyStr string
EmptyStr is the missing empty string for Go :)
var ( // ErrNoPipeData is returned when no data was read from the stdin pipe. ErrNoPipeData = errors.New("amoy: no pipe data") )
var ( // ErrWaitTimeout indicates timeout after waiting. ErrWaitTimeout = errors.New("amoy: wait timeout") )
var Now = time.Now
Now returns the current local time. This value is simply time.Now for consistency.
var ( // QuitRead indicates the arbitrary error means to quit from reading. QuitRead = errors.New("amoy: quit read by line") )
Functions ¶
func AccumulatedChannel ¶ added in v0.1.3
AccumulatedChannel returns a channel that accumulates values from given channel.
func AppStartTime ¶ added in v0.1.1
AppStartTime returns time when the app started.
func AppendFileBytes ¶ added in v0.1.0
AppendFileBytes writes the given data to the end of a file.
func AppendFileLines ¶ added in v0.1.0
AppendFileLines appends the given lines to the end of a text file.
func AppendFileString ¶ added in v0.1.0
AppendFileString appends the given content string to the end of a file.
func BackOffRetry ¶
BackOffRetry retries to execute given function with exponential backoff delay.
func BackOffRetryIf ¶
BackOffRetryIf retries to execute given function with exponential backoff delay if condition meets.
func BlockForever ¶ added in v0.1.3
func BlockForever()
BlockForever blocks current goroutine forever.
func CharBool ¶ added in v0.1.5
CharBool returns a Unicode char representing the given boolean value.
func ChooseWeightStrMap ¶ added in v0.0.16
ChooseWeightStrMap selects a random string key according to weights in value, or panics for invalid weights or internal errors.
func ComputeSI ¶
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
ContainsChinese returns true if the string contains Chinese characters (Hanzhi).
func ContainsJapanese ¶ added in v0.1.4
ContainsJapanese returns true if the string contains Japanese characters (Kanji, Hiragana, Katakana).
func ContainsKorean ¶ added in v0.1.4
ContainsKorean returns true if the string contains Korean characters (Hangul).
func CountDigit ¶ added in v0.1.2
CountDigit returns the number of digits of a number.
func CountFileLines ¶ added in v0.1.0
CountFileLines counts all lines from the given file (the line ending chars are not included).
func CountLines ¶
CountLines counts all lines from the given reader (the line ending chars are not included).
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
DayBegin returns the first moment of the given time in given location.
func DecodeBase36ToBytes ¶
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
DistinctInts returns a new slice with the same order but without duplicate int elements.
func DurationToString ¶ added in v0.1.4
DurationToString returns a string representation (dd:HH:MM:SS.sss) of given duration.
func EmojiBool ¶ added in v0.1.5
EmojiBool returns an emoji char representing the given boolean value.
func EmojiDone ¶ added in v0.1.5
EmojiDone returns an emoji char representing the given completion state.
func EncodeBytesAsBase36 ¶
EncodeBytesAsBase36 encodes a byte slice to base36 string.
func EncodeBytesAsBase36Bytes ¶
EncodeBytesAsBase36Bytes encodes a byte slice to base36.
func ExtractBottomLines ¶ added in v0.1.5
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
ExtractFirstLine extracts the first line from the given stream (the line ending chars are not included).
func ExtractLastLine ¶ added in v0.1.5
ExtractLastLine extracts the last line from the given stream (the line ending chars are not included).
func ExtractTopLines ¶ added in v0.1.5
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 FixedRetry ¶
FixedRetry retries to execute given function with consistent same delay.
func FixedRetryIf ¶
FixedRetryIf retries to execute given function with consistent same delay if condition meets.
func FractionCeil ¶
FractionCeil returns the least integer value greater than or equal to a/b.
func FractionFloor ¶
FractionFloor returns the greatest integer value less than or equal to a/b.
func FractionFractional ¶ added in v0.0.15
FractionFractional returns the fractional part of floating-point number represented by a/b.
func FractionRound ¶
FractionRound returns the nearest integer, rounding half away from zero of a/b.
func FractionTrunc ¶
FractionTrunc returns the integer value of a/b.
func Fractional ¶ added in v0.1.1
Fractional returns the fractional part of floating-point number f.
func FtoaWithDigits ¶
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 GenerateRSAKeys ¶ added in v0.0.16
GenerateRSAKeys generates RSA public and private key pair with given size for SSH.
func GetFingerprint ¶
GetFingerprint returns SHA1 hash of a string in fingerprint format.
func HumanizeBytes ¶
HumanizeBytes produces a human readable representation of an SI size.
HumanizeBytes(82854982) -> 83 MB
func HumanizeDuration ¶
HumanizeDuration humanizes time.Duration output to a meaningful value.
func HumanizeIBytes ¶
HumanizeIBytes produces a human readable representation of an IEC size.
HumanizeIBytes(82854982) -> 79 MiB
func IsTextFile ¶
IsTextFile loads and checks if the given path is a text file.
func LoadJSONFile ¶
LoadJSONFile loads object from the given JSON file.
func LocalDayBegin ¶ added in v0.0.15
LocalDayBegin returns the first moment of the given time in local timezone.
func LocalDayEnd ¶ added in v0.0.15
LocalDayEnd returns the last moment of the given time in local timezone.
func MergeIntSequence ¶ added in v0.1.5
MergeIntSequence merges int slices like [8, 8, 9, 10, 20, 12]. into sequences like "8-10,12,20".
func Milliseconds ¶ added in v0.0.14
Milliseconds returns a duration of given milliseconds.
func MustParseDateString ¶ added in v0.1.4
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
NewLocalDay returns the first moment of the given date in local timezone.
func NewUTCDay ¶ added in v0.1.0
NewUTCDay returns the first moment of the given date in UTC timezone.
func NoopZapLogger ¶
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 ParseHumanizedBytes ¶
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
ParseIntSequence parses sequences like "9-12,10,20" into slices of int like [9, 10, 11, 12, 20].
func ParseSI ¶
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 ¶
ParseUnixTime converts a unix timestamp to local time.
func PercentageStr ¶ added in v0.1.2
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 PrintColorfulJSON ¶
func PrintColorfulJSON(data interface{})
PrintColorfulJSON outputs commit in JSON with indent and syntax highlight to console.
func PrintJSON ¶
func PrintJSON(data interface{})
PrintJSON outputs commit in JSON with indent to console.
func PrintOneLineJSON ¶
func PrintOneLineJSON(data interface{})
PrintOneLineJSON outputs commit in JSON in one line.
func RandomDuration ¶ added in v0.0.16
RandomDuration returns a random duration between [min, max).
func RandomFloat ¶ added in v0.1.5
RandomFloat returns a random float64 number in [min, max).
func RandomTime ¶ added in v0.0.16
RandomTime returns a random time between [start, start+d) or [start+d, start) if d < 0.
func RandomTimeBetween ¶ added in v0.0.16
RandomTimeBetween returns a random time between [start, end).
func ReadByLine ¶
ReadByLine iterates the given Reader by lines (the line ending chars are not included).
func ReadFileByLine ¶ added in v0.1.0
ReadFileByLine iterates the given file by lines (the line ending chars are not included).
func ReadFileBytes ¶ added in v0.1.0
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
ReadFileLines reads all lines from the given file (the line ending chars are not included).
func ReadFileString ¶ added in v0.1.0
ReadFileString reads the whole named file and returns the contents as a string.
func ReadLines ¶
ReadLines reads all lines from the given reader (the line ending chars are not included).
func ReadStdinPipe ¶ added in v0.1.1
ReadStdinPipe reads stdin data via pipe and returns the data.
func RegexMatch ¶ added in v0.0.15
RegexMatch reports whether the string s contains any match of the regular expression pattern.
func RenderSparkline ¶ added in v0.1.6
RenderSparkline generates a sparkline string like ▅▆▂▂▅▇▂▂▃▆▆▆▅▃ from a slice of float64.
func RenderTableString ¶
RenderTableString renders the rows as table and returns as string for console.
func ReverseStr ¶
ReverseStr returns a reversed string of the given string.
func RoundToFixed ¶ added in v0.0.14
RoundToFixed returns the rounding floating number with given precision.
func RunCombinedCommand ¶
RunCombinedCommand runs the command and returns its combined standard output and standard error.
func RunQuietCommand ¶
RunQuietCommand runs the command quietly and returns no standard output nor standard error.
func RunSimpleCommand ¶
RunSimpleCommand simply runs the command and returns its standard output and standard error.
func RunWaitTimeout ¶ added in v0.0.16
RunWaitTimeout calls the task function, and waits for the result for the given max timeout.
func SI ¶
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 ¶
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 SaveJSONFile ¶
SaveJSONFile saves object as a JSON file.
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 ¶
SimpleRetry retries to execute given function for 3 times and with exponential backoff delay starting at 300ms.
func SimpleZapLogger ¶
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
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 StyleCrossOut ¶
StyleCrossOut renders a string with cross-out.
func StyleEmail ¶
StyleEmail renders a string of email with terminal colors.
func SubstrAfterFirst ¶
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 ¶
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 ¶
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 ¶
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 ¶
SubstrOrOrigin returns the original string if the target is missed in substr function.
func TrimUTF8BOM ¶
TrimUTF8BOM removes the leading UTF-8 byte order mark from bytes.
func TruncateStr ¶
TruncateStr renders a truncated string of the given length, or original one if it's shorter.
func UTCDayBegin ¶ added in v0.0.15
UTCDayBegin returns the first moment of the given time in UTC timezone.
func UTCDayEnd ¶ added in v0.0.15
UTCDayEnd returns the last moment of the given time in UTC timezone.
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 UnzipDir ¶
UnzipDir decompresses a zip archive, extracts all files and folders within the zip file to an output directory.
func WriteFileBytes ¶ added in v0.1.0
WriteFileBytes writes the given data into a file.
func WriteFileLines ¶ added in v0.1.0
WriteFileLines writes the given lines as a text file.
func WriteFileString ¶ added in v0.1.0
WriteFileString writes the given content string into a file.
func WriteLines ¶
WriteLines writes the given lines to a Writer.
func ZipContent ¶
func ZipContent(destZip string, content ArchiveContent) error
ZipContent compresses data entries into a single zip archive file.
Types ¶
type ArchiveContent ¶
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 ¶
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 ¶
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) Kill ¶
Kill causes the command to exit immediately, and does not wait until it has actually exited.
func (*Command) Stderr ¶
Stderr returns a slice holding the content of the standard error of the command.
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 NewDateFromTime ¶ added in v0.1.0
NewDateFromTime converts a time.Time into Date instance.
func (Date) Add ¶ added in v0.1.0
Add returns a Date instance for the duration after the given date.
func (Date) AddDay ¶ added in v0.1.0
AddDay returns a Date instance for given days after the current date.
func (Date) AddMonth ¶ added in v0.1.0
AddMonth returns a Date instance for given months after the current date.
func (Date) AddYear ¶ added in v0.1.0
AddYear returns a Date instance for given years after the current date.
func (Date) Before ¶ added in v0.1.0
Before indicates if current date is earlier than the given date.
func (Date) MarshalJSON ¶ added in v0.1.0
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
MarshalText implements the encoding.TextMarshaler interface. The time is formatted in ISO 8601 date format, with sub-second precision added if present.
func (Date) Time ¶ added in v0.1.0
Time returns a time.Time with given location for current instance.
func (*Date) UnmarshalJSON ¶ added in v0.1.0
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
UnmarshalText implements the encoding.TextUnmarshaler interface. The time is expected to be in ISO 8601 date format.
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 ¶
NewJSONLogger returns a Logger with given log path and debug mode and all output format is JSON.
func NewMonochromeLogger ¶ added in v0.1.2
NewMonochromeLogger returns a Logger with given log path and debug mode and output in console, save as json, and never cleans up.
func NewPersistentLogger ¶
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 ¶
GetLogLevel returns the log level of loggers inside the wrapper.
func (*Logger) LoggerSugared ¶
func (l *Logger) LoggerSugared() *zap.SugaredLogger
LoggerSugared returns a sugared zap logger inside the wrapper.
func (*Logger) SetLogLevel ¶
SetLogLevel sets the log level of loggers inside the wrapper.
type NamedValues ¶
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 RetryIfFunc ¶
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 ¶
Elapsed returns the total elapsed time measured by the current instance.
func (*Stopwatch) ElapsedMilliseconds ¶ added in v0.0.16
ElapsedMilliseconds returns the total elapsed time measured by the current instance, in milliseconds.
Source Files ¶
- base36.go
- channel.go
- date.go
- discard.go
- emoji.go
- exec_run.go
- exec_start.go
- file.go
- hash.go
- http.go
- humanize_bytes.go
- humanize_duration.go
- humanize_ftoa.go
- humanize_si.go
- json.go
- line.go
- logger.go
- logger_set.go
- map.go
- math.go
- minmax.go
- print.go
- random.go
- regex.go
- render.go
- retry.go
- rsa.go
- run.go
- sequence.go
- shell.go
- sleep.go
- slogan.go
- stopwatch.go
- strconv.go
- string.go
- style.go
- time.go
- uuid.go
- zip.go