goutils

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2020 License: MIT Imports: 15 Imported by: 1

README

goutils

Description

Some common utilities to make your development more productive.

Install

go get github.com/gaols/goutils

utilities

stringutils

if you come from Java, you should familiar with the those apis. It's the go implementation of apache commons for string manipulation.

import "github.com/gaols/goutils"

goutils.Reverse("fox")                // out: xof
goutils.LeftPad("fox", 5, 'z')        // out: zzfox
goutils.RightPad("fox", 5, 'z')       // out: foxzz
goutils.IsBlank(" ")                  // out: true
goutils.IsBlank("a")                  // out: false
goutils.IsEmpty("")                   // out: true
goutils.IsEmpty(" ")                  // out: false
goutils.DefaultIfBlank(" ", "hello")  // out: hello
goutils.DefaultIfBlank("c", "hello")  // out: c
goutils.DefaultIfEmpty("", "hello")   // out: hello
goutils.DefaultIfEmpty("c", "hello")  // out: c
goutils.Substring("hello", 0, 1)      // out: h
goutils.IsAnyBlank("hello", "")       // out: true
goutils.IsAnyBlank("hello")           // out: false
dateutils

date utils has a lot of date related sugar methods.

goutils.Today()
goutils.Yesterday()
goutils.BeginningOfThisWeek()
goutils.BeginningOfThisMonth()
goutils.BeginningOfThisYear()
goutils.LastWeek()
goutils.LastMonth()
goutils.LastYear()
// ... and many others
timeutils
// assumes time now is: 2017-12-27 21:15:15
goutils.FmtTime(time.Now(), "-datetime")      // out: 2017-12-27 21:15:15
goutils.FmtTime(time.Now(), "-datetime-")     // out: 2017-12-27 21:15
goutils.FmtTime(time.Now(), "-datetime--")    // out: 2017-12-27 21
goutils.FmtTime(time.Now(), "-date")          // out: 2017-12-27
goutils.FmtTime(time.Now(), "time")           // out: 21:15:15
goutils.FmtTime(time.Now(), "time-")          // out: 21:15
goutils.FmtTime(time.Now(), "time--")         // out: 21

goutils.FmtTime(time.Now(), "/datetime")      // out: 2017/12/27 21:15:15
goutils.FmtTime(time.Now(), "/datetime-")     // out: 2017/12/27 21:15
goutils.FmtTime(time.Now(), "/datetime--")    // out: 2017/12/27 21
goutils.FmtTime(time.Now(), "/date")          // out: 2017/12/27

goutils.FmtTime(time.Now(), ".datetime")      // out: 2017.12.27 21:15:15
goutils.FmtTime(time.Now(), ".datetime-")     // out: 2017.12.27 21:15
goutils.FmtTime(time.Now(), ".datetime--")    // out: 2017.12.27 21
goutils.FmtTime(time.Now(), ".date")          // out: 2017.12.27

goutils.FmtTime(time.Now(), "xzzz")           // error
goutils.MustFmtTime(time.Now(), "xzzz")       // panic
goutils.MustParseTime("2017-12-27", "-date")  // time object@2017-12-27

terminal color utils

goutils.GreenText("%s is very cool", "something")
goutils.RedText("this text will be red")

if more colorized text is required, use github.com/fatih/color instead.

input utils

goutils.Confirm will block the program and force user to make a choice before doing any other things.

goutils.Confirm("are you sure(y/n)?", []string {"y"}, []string {"n"}, func() {
  // do something when user input 'n'
})

Documentation

Index

Constants

View Source
const (
	// TimeUnitTypeSecond as second
	TimeUnitTypeSecond int = 0
	// TimeUnitTypeMinute as minute
	TimeUnitTypeMinute int = 1
	// TimeUnitTypeHour as hour
	TimeUnitTypeHour int = 2
)
View Source
const (
	// TypeStdout is type of stdout
	TypeStdout = 0
	// TypeStderr is type of stderr
	TypeStderr = 1
)

Variables

This section is empty.

Functions

func BeginningOfDate

func BeginningOfDate(t time.Time) time.Time

BeginningOfDate returns the beginning date of a time.

func BeginningOfMonth added in v1.2.1

func BeginningOfMonth(t time.Time) time.Time

BeginningOfMonth returns the first date of a month where t belongs to.

func BeginningOfThisMonth added in v1.2.1

func BeginningOfThisMonth() time.Time

BeginningOfThisMonth returns the first date of this month.

func BeginningOfThisWeek added in v1.2.0

func BeginningOfThisWeek() time.Time

BeginningOfThisWeek returns the beginning date of this week.

func BeginningOfThisYear added in v1.2.1

func BeginningOfThisYear() time.Time

BeginningOfThisYear returns the first date of this year.

func BeginningOfWeek added in v1.2.0

func BeginningOfWeek(t time.Time) time.Time

BeginningOfWeek return the first date of the week where t belongs to.

func BeginningOfYear added in v1.2.1

func BeginningOfYear(t time.Time) time.Time

BeginningOfYear returns the first date of a year where t belongs to.

func Confirm added in v1.2.1

func Confirm(query string, positiveChoices, negativeChoices []string, negativeAction func())

Confirm force input string must be in positiveChoices or negativeChoices, if false choice is selected, negative action will be invoked. This function can be useful that if you want user must make a choice before doing anything further.

func ContainsAnyInt added in v1.2.0

func ContainsAnyInt(arr []int, vals ...int) bool

ContainsAnyInt return true if arr contains any value in vals.

func ContainsAnyIntFunc added in v1.2.0

func ContainsAnyIntFunc(arr []int, f func(int) bool) bool

ContainsAnyIntFunc return true if arr contains any value v when f(v) evalutes to true.

func ContainsAnyStr added in v1.2.0

func ContainsAnyStr(arr []string, vals ...string) bool

ContainsAnyStr return true if arr contains any value in vals.

func ContainsAnyStrFunc added in v1.2.0

func ContainsAnyStrFunc(arr []string, f func(string) bool) bool

ContainsAnyStrFunc return true if arr contains any value v when f(v) evalutes to true.

func ContainsInt added in v1.2.0

func ContainsInt(arr []int, val int) bool

ContainsInt returns true if arr contains val.

func ContainsStr added in v1.2.0

func ContainsStr(arr []string, val string) bool

ContainsStr returns true if arr contains val.

func DaysAfter

func DaysAfter(t time.Time, days int) time.Time

DaysAfter returns the time add specified days.

func DaysAgo

func DaysAgo(t time.Time, days int) time.Time

DaysAgo returns the time subtract specified days.

func DaysBetween

func DaysBetween(startTime, endTime time.Time) int

DaysBetween calc days between two days. goutils.DaysBetween(goutils.Yesterday(), goutils.Today()) = 1 goutils.DaysBetween(goutils.Today(), goutils.Yesterday()) = -1

func DefaultIfBlank

func DefaultIfBlank(str, defaultStr string) string

DefaultIfBlank Returns either the passed in string, or if the string is whitespace, empty (""), the value of default string.

func DefaultIfEmpty

func DefaultIfEmpty(str, defaultStr string) string

DefaultIfEmpty Returns either the passed in string, or if the string is empty (""), the value of default string.

func EndOfDate added in v1.2.1

func EndOfDate(t time.Time) time.Time

EndOfDate returns the ending nano of a date where t belongs to.

func EndOfThisMonth added in v1.2.1

func EndOfThisMonth() time.Time

EndOfThisMonth returns the last date of this month.

func EndOfThisYear added in v1.2.1

func EndOfThisYear() time.Time

EndOfThisYear returns the last date of this year.

func EndingOfDate

func EndingOfDate(t time.Time) time.Time

EndingOfDate returns the ending nano of a date where t belongs to. Deprecated: Use EndOfDate instead.

func Escape added in v1.2.0

func Escape(sql string) string

Escape the sql to prevent sql injection. Simply a copy from https://gist.github.com/siddontang/8875771

func FmtTime

func FmtTime(time time.Time, layout string) (string, error)

FmtTime format time by specified layout.

func GreenText added in v1.2.1

func GreenText(format string, a ...interface{})

GreenText prints green colored text.

func InParam added in v1.2.0

func InParam(ins []string) string

InParam is a helper method to build in params of sql.

func Int2Str added in v1.2.1

func Int2Str(i int) string

Int2Str convert int to string.

func IsAnyBlank

func IsAnyBlank(strList ...string) bool

IsAnyBlank checks if any one of the CharSequences are blank ("") or whitespace only.

func IsBlank

func IsBlank(str string) bool

IsBlank Checks if a string is whitespace, empty ("").

func IsDir

func IsDir(path string) bool

IsDir tests whether a path is dir or not, true if path is dir, false otherwise.

func IsEmpty

func IsEmpty(str string) bool

IsEmpty Checks if a string is whitespace, empty ("").

func IsEqualsAny

func IsEqualsAny(val string, vals ...string) bool

IsEqualsAny tests whether a string equals any string provided.

func IsFileExists

func IsFileExists(filepath string) bool

IsFileExists tests existence of specified file.

func IsNotBlank

func IsNotBlank(str string) bool

IsNotBlank Checks if a string is not empty (""), not null and not whitespace only.

func IsNotEmpty

func IsNotEmpty(str string) bool

IsNotEmpty Checks if a string is not empty ("").

func IsRegular

func IsRegular(path string) bool

IsRegular tests whether a path is a regular file.

func LastMonth added in v1.2.1

func LastMonth() time.Time

LastMonth returns the first date of last month.

func LastWeek added in v1.2.1

func LastWeek() time.Time

LastWeek returns monday of last week.

func LastYear added in v1.2.1

func LastYear() time.Time

LastYear returns the first date of last year.

func LeftPad

func LeftPad(str string, size int, padChar rune) string

LeftPad pad a String with a specified character on the left. WARNING: string to pad should be uft8-encoded!

goutils.LeftPad("", 3, 'z') = "zzz" goutils.LeftPad("bat", 3, 'z') = "bat" goutils.LeftPad("bat", 5, 'z') = "zzbat" goutils.LeftPad("bat", 1, 'z') = "bat" goutils.LeftPad("bat", -1, 'z') = "bat"

func Local

func Local(localCmd string, paras ...interface{}) (out string, err error)

Local run the command in localhost https://studygolang.com/articles/4004 <- run shell command and read output line by line https://studygolang.com/articles/7767 <- run command without known args

func MaxInt added in v1.2.1

func MaxInt() int

MaxInt guess the max int value.

func MustFmtTime

func MustFmtTime(time time.Time, layout string) string

MustFmtTime format time by specified layout, will panic if layout is invalid.

func MustParseLocaltime

func MustParseLocaltime(toParseTime, layout string) time.Time

MustParseLocaltime time with zone set to local, will panic if layout specified is invalid. parsable layout can be [-datetime|-datetime-|-datetime--|-date|-date-|-date--|time|time-|time--] and any other layout format that can pass to time.ParseInLocation

func ParseLocaltime

func ParseLocaltime(toParseTime, layout string) (time.Time, error)

ParseLocaltime time with zone set to local. parsable layout can be [-datetime|-datetime-|-datetime--|-date|-date-|-date--|time|time-|time--] and any other layout format that can pass to time.ParseInLocation

func RandDuration

func RandDuration(lower, upper, timeUnitType int) time.Duration

RandDuration generate pseudo time duration between lower and upper with lower and upper bound inclusively.

func ReadLine

func ReadLine(filepath string, handler func(line string, index uint64)) error

ReadLine read file line by line and calls handler with each line and index.

func RedText added in v1.2.1

func RedText(format string, a ...interface{})

RedText prints red colored text.

func RemoveTrailingSlash

func RemoveTrailingSlash(path string) string

RemoveTrailingSlash remove the last slash of a path except the root path.

func Reverse

func Reverse(s string) string

Reverse reverse a string. WARNING: This does not work with combining characters. check https://stackoverflow.com/questions/1752414/how-to-reverse-a-string-in-go for more stories.

goutils.Reverse("hello") = "olleh"

func ReversePreservingCombiningCharacters

func ReversePreservingCombiningCharacters(s string) string

ReversePreservingCombiningCharacters reverse a string preserving combining characters. The implementation is copied from http://rosettacode.org/wiki/Reverse_a_string#Go goutils.ReversePreservingCombiningCharacters("The quick bròwn 狐 jumped over the lazy 犬") = "犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT"

func RightPad

func RightPad(str string, size int, padChar rune) string

RightPad right pad a String with a specified character. WARNING: string to pad should be uft8-encoded!

goutils.RightPad("", 3, 'z') = "zzz" goutils.RightPad("bat", 3, 'z') = "bat" goutils.RightPad("bat", 5, 'z') = "batzz" goutils.RightPad("bat", 1, 'z') = "bat" goutils.RightPad("bat", -1, 'z') = "bat"

func RtLocal

func RtLocal(localCmd string, lineHandler func(line string, lineType int8), paras ...interface{}) error

RtLocal run the command in localhost and get command output realtime.

func Str2Int added in v1.2.1

func Str2Int(str string) (int, error)

Str2Int convert string to int.

func Substring

func Substring(str string, i, j int) string

Substring Returns a substring of str in range(i, j).

func SumInt added in v1.2.1

func SumInt(a ...int) int

SumInt do summary of all int paras.

Warning: if no para provided, zero will be returned. this func does not care about overflow, using at own risk.

func SumIntSlice added in v1.2.1

func SumIntSlice(s []int) int

SumIntSlice do summary of the int slice.

Warning: if empty or nil slice is provided, zero will be returned. this func does not care about overflow, using at own risk.

func Tar

func Tar(tgzPath, targetPath string) error

Tar pack the targetPath and put tarball to tgzPath, targetPath and tgzPath should both the absolute path.

func ToInt added in v1.2.1

func ToInt(v interface{}) (int, error)

ToInt convert string and any other int/float types to int. Warning: the result my be truncated if number overflows int.

func ToIntWithDefault added in v1.2.1

func ToIntWithDefault(v interface{}, defVal int) int

ToIntWithDefault tries to convert string and any other int types to int, return a default value provided if error occurs. Warning: the result my be truncated if number overflows int.

func Today

func Today() time.Time

Today returns the beginning date of today.

func Tomorrow

func Tomorrow() time.Time

Tomorrow returns the beginning date of tomorrow.

func Trim

func Trim(str string) string

Trim returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

func UnTar

func UnTar(tgzPath, targetPath string) error

UnTar unpack the tarball specified by tgzPath and extract it to the path specified by targetPath

func Yesterday

func Yesterday() time.Time

Yesterday returns the beginning date of yesterday.

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