Documentation ¶
Overview ¶
Package goutil is a common and useful toolkit for Go project development.
Inclusion criteria:
- Only rely on the Go standard package
- Functions or lightweight packages
- Non-business related general tools
Index ¶
- Constants
- Variables
- func AESCBCDecrypt(cipherkey, ciphertext []byte, useBase64 ...bool) ([]byte, error)
- func AESCBCEncrypt(cipherkey, plaintext []byte, useBase64 ...bool) []byte
- func AESCTRDecrypt(cipherkey, ciphertext []byte, useBase64 ...bool) ([]byte, error)
- func AESCTREncrypt(cipherkey, plaintext []byte, useBase64 ...bool) []byte
- func AESDecrypt(cipherkey, ciphertext []byte, useBase64 ...bool) ([]byte, error)
- func AESEncrypt(cipherkey, plaintext []byte, useBase64 ...bool) []byte
- func AddrInt(i int) *int
- func BytesToString(b []byte) string
- func CamelString(s string) string
- func CodePointToUTF8(str string, base int) string
- func CopyStrings(a []string) []string
- func DereferenceIfaceValue(v reflect.Value) reflect.Value
- func DereferenceImplementType(v reflect.Value) reflect.Type
- func DereferencePtrValue(v reflect.Value) reflect.Value
- func DereferenceSlice(v reflect.Value) reflect.Value
- func DereferenceType(t reflect.Type) reflect.Type
- func DereferenceValue(v reflect.Value) reflect.Value
- func ExtranetIP() (ip string, err error)
- func FileExist(name string) (existed bool, isDir bool)
- func FileExists(name string) (existed bool)
- func FilepathAbsolute(paths []string) ([]string, error)
- func FilepathAbsoluteMap(paths []string) (map[string]string, error)
- func FilepathContains(basepath string, subpaths []string) error
- func FilepathDistinct(paths []string, toAbs bool) ([]string, error)
- func FilepathFromSlash(paths []string) []string
- func FilepathRelative(basepath string, targpaths []string) ([]string, error)
- func FilepathRelativeMap(basepath string, targpaths []string) (map[string]string, error)
- func FilepathSame(path1, path2 string) (bool, error)
- func FilepathSlashInsensitive(path string) string
- func FilepathSplitExt(filename string, slashInsensitive ...bool) (root, ext string)
- func FilepathStem(filename string, slashInsensitive ...bool) string
- func FilepathToSlash(paths []string) []string
- func Fnv1aToUint32(b []byte) uint32
- func Fnv1aToUint64(b []byte) uint64
- func GetCallLine(calldepth int) string
- func GetFirstGopath(allowAutomaticGuessing bool) (gopath string, err error)
- func GetGopaths() []string
- func GrepFile(patten string, filename string) (lines []string, err error)
- func HTMLEntityToUTF8(str string, base int) string
- func Indent(text, prefix string) string
- func InitAndGetString(strPtr *string, def string) string
- func InitPointer(v reflect.Value) bool
- func Int32sDistinct(a []int32) (set []int32)
- func Int64sDistinct(a []int64) (set []int64)
- func InterfacesDistinct(a []interface{}) (set []interface{})
- func IntersectStrings(set1, set2 []string) []string
- func IntranetIP() (string, error)
- func IntsDistinct(a []int) (set []int)
- func IsCompositionMethod(method reflect.Method) bool
- func IsExportedName(name string) bool
- func IsExportedOrBuiltinType(t reflect.Type) bool
- func IsGoTest() bool
- func IsLittleEndian() bool
- func JsQueryEscape(s string) string
- func JsQueryUnescape(s string) (string, error)
- func LintCamelString(name string) string
- func Md5(b []byte) string
- func MkdirAll(path string, perm ...os.FileMode) error
- func ObjectName(obj interface{}) string
- func PanicTrace(kb int) []byte
- func RandomBytes(n int) []byte
- func ReferenceSlice(v reflect.Value, ptrDepth int) reflect.Value
- func ReferenceType(t reflect.Type, ptrDepth int) reflect.Type
- func ReferenceValue(v reflect.Value, ptrDepth int) reflect.Value
- func RelPath(targpath string) string
- func RemoveAllFromInt32s(set []int32, a int32) []int32
- func RemoveAllFromInt64s(set []int64, a int64) []int64
- func RemoveAllFromInterfaces(set []interface{}, a interface{}) []interface{}
- func RemoveAllFromInts(set []int, a int) []int
- func RemoveAllFromStrings(set []string, a string) []string
- func RemoveFromInt32s(set []int32, a int32) []int32
- func RemoveFromInt64s(set []int64, a int64) []int64
- func RemoveFromInterfaces(set []interface{}, a interface{}) []interface{}
- func RemoveFromInts(set []int, a int) []int
- func RemoveFromStrings(set []string, a string) []string
- func ReplaceFile(filename string, start, end int, newContent string) error
- func RewriteFile(filename string, fn func(content []byte) (newContent []byte, err error)) error
- func RewriteToFile(filename, newfilename string, ...) error
- func SearchFile(filename string, paths ...string) (fullpath string, err error)
- func SelfChdir()
- func SelfDir() string
- func SelfPath() string
- func SetToInt32s(set []int32, a int32) []int32
- func SetToInt64s(set []int64, a int64) []int64
- func SetToInterfaces(set []interface{}, a interface{}) []interface{}
- func SetToInts(set []int, a int) []int
- func SetToStrings(set []string, a ...string) []string
- func Sha1(b []byte) string
- func Sha256(b []byte) string
- func Sha512(b []byte) string
- func SnakeString(s string) string
- func SpaceInOne(s string) string
- func StringMarshalJSON(s string, escapeHTML bool) []byte
- func StringToBytes(s string) []byte
- func StringsConvert(a []string, fn func(string) (string, error)) ([]string, error)
- func StringsConvertMap(a []string, fn func(string) (string, error)) (map[string]string, error)
- func StringsDistinct(a []string) (set []string)
- func StringsToBools(a []string, emptyAsZero ...bool) ([]bool, error)
- func StringsToFloat32s(a []string, emptyAsZero ...bool) ([]float32, error)
- func StringsToFloat64s(a []string, emptyAsZero ...bool) ([]float64, error)
- func StringsToInt16s(a []string, emptyAsZero ...bool) ([]int16, error)
- func StringsToInt32s(a []string, emptyAsZero ...bool) ([]int32, error)
- func StringsToInt64s(a []string, emptyAsZero ...bool) ([]int64, error)
- func StringsToInt8s(a []string, emptyAsZero ...bool) ([]int8, error)
- func StringsToInts(a []string, emptyAsZero ...bool) ([]int, error)
- func StringsToUint16s(a []string, emptyAsZero ...bool) ([]uint16, error)
- func StringsToUint32s(a []string, emptyAsZero ...bool) ([]uint32, error)
- func StringsToUint64s(a []string, emptyAsZero ...bool) ([]uint64, error)
- func StringsToUint8s(a []string, emptyAsZero ...bool) ([]uint8, error)
- func StringsToUints(a []string, emptyAsZero ...bool) ([]uint, error)
- func TarGz(src, dst string, includePrefix bool, logOutput func(string, ...interface{}), ...) (err error)
- func TarGzTo(src string, dstWriter io.Writer, includePrefix bool, ...) (err error)
- func URLRandomString(n int) string
- func WalkDirs(targpath string, suffixes ...string) (dirlist []string)
- func WriteFile(filename string, data []byte, perm ...os.FileMode) error
- func WritePidFile(pidFile ...string)
- type KVData
- func (k KVData) Get(key string) (value interface{}, exists bool)
- func (k KVData) GetBool(key string) (b bool)
- func (k KVData) GetDuration(key string) (d time.Duration)
- func (k KVData) GetFloat64(key string) (f64 float64)
- func (k KVData) GetInt(key string) (i int)
- func (k KVData) GetInt64(key string) (i64 int64)
- func (k KVData) GetString(key string) (s string)
- func (k KVData) GetStringMap(key string) (sm map[string]interface{})
- func (k KVData) GetStringMapString(key string) (sms map[string]string)
- func (k KVData) GetStringMapStringSlice(key string) (smss map[string][]string)
- func (k KVData) GetStringSlice(key string) (ss []string)
- func (k KVData) GetTime(key string) (t time.Time)
- func (k KVData) MustGet(key string) interface{}
- type Map
- type Random
Examples ¶
Constants ¶
const ( // Is64BitPlatform Whether the current system is a 64-bit platform Is64BitPlatform bool = (32 << (^uint(0) >> 63)) == 64 // Is32BitPlatform Whether the current system is a 32-bit platform Is32BitPlatform bool = (32 << (^uint(0) >> 63)) == 0 )
const IS_GO_TEST = "IS_GO_TEST"
Variables ¶
var DEFAULT_PID_FILE = "log/PID"
DEFAULT_PID_FILE the default PID file name
Functions ¶
func AESCBCDecrypt ¶
AESCBCDecrypt hex decodes a piece of data and then decrypts it using CBC mode. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func AESCBCEncrypt ¶
AESCBCEncrypt uses CBC mode to encrypt a piece of data and then encodes it in hex. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func AESCTRDecrypt ¶
AESCTRDecrypt hex decodes a piece of data and then decrypts it using CTR mode. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func AESCTREncrypt ¶
AESCTREncrypt uses CTR mode to encrypt a piece of data and then encodes it in hex. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func AESDecrypt ¶
AESDecrypt hex decodes a piece of data and then decrypts it using ECB mode. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func AESEncrypt ¶
AESEncrypt uses ECB mode to encrypt a piece of data and then encodes it in hex. The cipherkey argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func BytesToString ¶
BytesToString convert []byte type to string type.
func CamelString ¶
CamelString converts the accepted string to a camel string (xx_yy to XxYy)
func CodePointToUTF8 ¶
CodePointToUTF8 converts Unicode Code Point to UTF-8. e.g.: CodePointToUTF8(`{"info":[["color","\u5496\u5561\u8272\u7c\u7eff\u8272"]]}`, 16) => `{"info":[["color","咖啡色|绿色"]]}`
func CopyStrings ¶
CopyStrings creates a copy of the string slice.
func DereferenceIfaceValue ¶
DereferenceIfaceValue returns the value of the underlying type that implements the interface v.
func DereferenceImplementType ¶
DereferenceImplementType returns the underlying type of the value that implements the interface v.
func DereferencePtrValue ¶
DereferencePtrValue returns the underlying non-pointer type value.
func DereferenceSlice ¶
DereferenceSlice convert []*T to []T.
func DereferenceType ¶
DereferenceType dereference, get the underlying non-pointer type.
func DereferenceValue ¶
DereferenceValue dereference and unpack interface, get the underlying non-pointer and non-interface value.
func ExtranetIP ¶
ExtranetIP get external IP addr. NOTE: Query IP information from the service API: http://pv.sohu.com/cityjson?ie=utf-8
func FileExists ¶
FileExists reports whether the named file or directory exists.
func FilepathAbsolute ¶
FilepathAbsolute returns the absolute paths.
func FilepathAbsoluteMap ¶
FilepathAbsoluteMap returns the absolute paths map.
func FilepathContains ¶
FilepathContains checks if the basepath path contains the subpaths.
func FilepathDistinct ¶
FilepathDistinct removes the same path and return in the original order. If toAbs is true, return the result to absolute paths.
func FilepathFromSlash ¶
FilepathFromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.
func FilepathRelative ¶
FilepathRelative returns the relative paths.
func FilepathRelativeMap ¶
FilepathRelativeMap returns the relative paths map.
func FilepathSame ¶
FilepathSame checks if the two paths are the same.
func FilepathSlashInsensitive ¶
FilepathSlashInsensitive ignore the difference between the slash and the backslash, and convert to the same as the current system.
func FilepathSplitExt ¶
FilepathSplitExt splits the filename into a pair (root, ext) such that root + ext == filename, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns (”, '.cshrc').
func FilepathStem ¶
FilepathStem returns the stem of filename. Example:
FilepathStem("/root/dir/sub/file.ext") // output "file"
NOTE:
If slashInsensitive is empty, default is false.
func FilepathToSlash ¶
FilepathToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.
func Fnv1aToUint32 ¶
Fnv1aToUint32 returns the 32-bit FNV-1a hash sum of b.
func Fnv1aToUint64 ¶
Fnv1aToUint64 returns the 64-bit FNV-1a hash sum of b.
func GetFirstGopath ¶
GetFirstGopath gets the first $GOPATH value.
func GrepFile ¶
GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read
func HTMLEntityToUTF8 ¶
HTMLEntityToUTF8 converts HTML Unicode to UTF-8. e.g.: HTMLEntityToUTF8(`{"info":[["color","ᕸᖹ⁐c;eff;⁐"]]}`, 16) => `{"info":[["color","咖啡色|绿色"]]}`
func InitAndGetString ¶
InitAndGetString if strPtr is empty string, initialize it with def, and return the final value.
func Int32sDistinct ¶
Int32sDistinct creates a int32 set that removes the same element32s and returns them in their original order.
func Int64sDistinct ¶
Int64sDistinct creates a int64 set that removes the same element64s and returns them in their original order.
func InterfacesDistinct ¶
func InterfacesDistinct(a []interface{}) (set []interface{})
InterfacesDistinct creates a interface{} set that removes the same elements and returns them in their original order.
func IntersectStrings ¶
IntersectStrings calculate intersection of two sets.
func IntsDistinct ¶
IntsDistinct creates a int set that removes the same elements and returns them in their original order.
func IsCompositionMethod ¶
IsCompositionMethod determines whether the method inherits from the anonymous field of the struct.
func IsExportedName ¶
IsExportedName is this an exported - upper case - name?
func IsExportedOrBuiltinType ¶
IsExportedOrBuiltinType is this type exported or a builtin?
func IsLittleEndian ¶
func IsLittleEndian() bool
IsLittleEndian determine whether the current system is little endian.
func JsQueryEscape ¶
JsQueryEscape escapes the string in javascript standard so it can be safely placed inside a URL query.
func JsQueryUnescape ¶
JsQueryUnescape does the inverse transformation of JsQueryEscape, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.
func LintCamelString ¶
LintCamelString converts the accepted string to a camel string (xx_id to XxID) NOTE:
support common initialisms
func MkdirAll ¶
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil. If perm is empty, default use 0755.
func ObjectName ¶
func ObjectName(obj interface{}) string
ObjectName gets the type name of the object
func RandomBytes ¶
RandomBytes returns securely generated random bytes. It will panic if the system's secure random number generator fails to function correctly.
func ReferenceSlice ¶
ReferenceSlice convert []T to []*T, the ptrDepth is the count of '*'.
func ReferenceType ¶
ReferenceType convert T to *T, the ptrDepth is the count of '*'.
func ReferenceValue ¶
ReferenceValue convert T to *T, the ptrDepth is the count of '*'.
func RemoveAllFromInt32s ¶
RemoveAllFromInt32s removes all the a element from the int32 set.
func RemoveAllFromInt64s ¶
RemoveAllFromInt64s removes all the a element from the int64 set.
func RemoveAllFromInterfaces ¶
func RemoveAllFromInterfaces(set []interface{}, a interface{}) []interface{}
RemoveAllFromInterfaces removes all the a element from the interface{} set.
func RemoveAllFromInts ¶
RemoveAllFromInts removes all the a element from the int set.
func RemoveAllFromStrings ¶
RemoveAllFromStrings removes all the a element from the string set.
func RemoveFromInt32s ¶
RemoveFromInt32s removes the first element from the int32 set.
func RemoveFromInt64s ¶
RemoveFromInt64s removes the first element from the int64 set.
func RemoveFromInterfaces ¶
func RemoveFromInterfaces(set []interface{}, a interface{}) []interface{}
RemoveFromInterfaces removes the first element from the interface{} set.
func RemoveFromInts ¶
RemoveFromInts removes the first element from the int set.
func RemoveFromStrings ¶
RemoveFromStrings removes the first element from the string set.
func ReplaceFile ¶
ReplaceFile replaces the bytes selected by [start, end] with the new content.
func RewriteFile ¶
RewriteFile rewrites the file.
func RewriteToFile ¶
func RewriteToFile(filename, newfilename string, fn func(content []byte) (newContent []byte, err error)) error
RewriteToFile rewrites the file to newfilename. If newfilename already exists and is not a directory, replaces it.
func SearchFile ¶
SearchFile Search a file in paths. this is often used in search config file in /etc ~/
func SetToInt32s ¶
SetToInt32s sets a element to the int32 set.
func SetToInt64s ¶
SetToInt64s sets a element to the int64 set.
func SetToInterfaces ¶
func SetToInterfaces(set []interface{}, a interface{}) []interface{}
SetToInterfaces sets a element to the interface{} set.
func SetToStrings ¶
SetToStrings sets a element to the string set.
func SnakeString ¶
SnakeString converts the accepted string to a snake string (XxYy to xx_yy)
func SpaceInOne ¶
SpaceInOne combines multiple consecutive space characters into one.
func StringMarshalJSON ¶
StringMarshalJSON converts the string to JSON byte stream.
Example ¶
s := `<>&{}""` fmt.Printf("%s\n", StringMarshalJSON(s, true)) fmt.Printf("%s\n", StringMarshalJSON(s, false))
Output: "\u003c\u003e\u0026{}\"\"" "<>&{}\"\""
func StringToBytes ¶
StringToBytes convert string type to []byte type. NOTE: panic if modify the member value of the []byte.
func StringsConvert ¶
StringsConvert converts the string slice to a new slice using fn. If fn returns error, exit the conversion and return the error.
func StringsConvertMap ¶
StringsConvertMap converts the string slice to a new map using fn. If fn returns error, exit the conversion and return the error.
func StringsDistinct ¶
StringsDistinct creates a string set that removes the same elements and returns them in their original order.
func StringsToBools ¶
StringsToBools converts string slice to bool slice.
func StringsToFloat32s ¶
StringsToFloat32s converts string slice to float32 slice.
func StringsToFloat64s ¶
StringsToFloat64s converts string slice to float64 slice.
func StringsToInt16s ¶
StringsToInt16s converts string slice to int16 slice.
func StringsToInt32s ¶
StringsToInt32s converts string slice to int32 slice.
func StringsToInt64s ¶
StringsToInt64s converts string slice to int64 slice.
func StringsToInt8s ¶
StringsToInt8s converts string slice to int8 slice.
func StringsToInts ¶
StringsToInts converts string slice to int slice.
func StringsToUint16s ¶
StringsToUint16s converts string slice to uint16 slice.
func StringsToUint32s ¶
StringsToUint32s converts string slice to uint32 slice.
func StringsToUint64s ¶
StringsToUint64s converts string slice to uint64 slice.
func StringsToUint8s ¶
StringsToUint8s converts string slice to uint8 slice.
func StringsToUints ¶
StringsToUints converts string slice to uint slice.
func TarGz ¶
func TarGz(src, dst string, includePrefix bool, logOutput func(string, ...interface{}), ignoreElem ...string) (err error)
TarGz compresses and archives tar.gz file.
func TarGzTo ¶
func TarGzTo(src string, dstWriter io.Writer, includePrefix bool, logOutput func(string, ...interface{}), ignoreElem ...string) (err error)
TarGzTo compresses and archives tar.gz to dst writer.
func URLRandomString ¶
URLRandomString returns a URL-safe, base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.
func WalkDirs ¶
WalkDirs traverses the directory, return to the relative path. You can specify the suffix.
func WriteFile ¶
WriteFile writes file, and automatically creates the directory if necessary. NOTE:
If perm is empty, automatically determine the file permissions based on extension.
func WritePidFile ¶
func WritePidFile(pidFile ...string)
WritePidFile writes the current PID to the specified file.
Types ¶
type KVData ¶
type KVData map[string]interface{}
KVData key-value data
func (KVData) Get ¶
Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)
func (KVData) GetDuration ¶
GetDuration returns the value associated with the key as a duration.
func (KVData) GetFloat64 ¶
GetFloat64 returns the value associated with the key as a float64.
func (KVData) GetStringMap ¶
GetStringMap returns the value associated with the key as a map of interfaces.
func (KVData) GetStringMapString ¶
GetStringMapString returns the value associated with the key as a map of strings.
func (KVData) GetStringMapStringSlice ¶
GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
func (KVData) GetStringSlice ¶
GetStringSlice returns the value associated with the key as a slice of strings.
type Map ¶
type Map interface { // Load returns the value stored in the map for a key, or nil if no // value is present. // The ok result indicates whether value was found in the map. Load(key interface{}) (value interface{}, ok bool) // Store sets the value for a key. Store(key, value interface{}) // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. // The loaded result is true if the value was loaded, false if stored. LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) // Range calls f sequentially for each key and value present in the map. // If f returns false, range stops the iteration. Range(f func(key, value interface{}) bool) // Random returns a pair kv randomly. // If exist=false, no kv data is exist. Random() (key, value interface{}, exist bool) // Delete deletes the value for a key. Delete(key interface{}) // Clear clears all current data in the map. Clear() // Len returns the length of the map. Len() int }
Map is a concurrent map with loads, stores, and deletes. It is safe for multiple goroutines to call a Map's methods concurrently.
type Random ¶
type Random struct {
// contains filtered or unexported fields
}
Random random string creator.
func (*Random) RandomString ¶
RandomString returns a base64 encoded securely generated random string. It will panic if the system's secure random number generator fails to function correctly. The length n must be an integer multiple of 4, otherwise the last character will be padded with `=`.
func (*Random) RandomStringWithTime ¶
RandomStringWithTime returns a random string with UNIX timestamp(in second). unixTs: range [0,56800235583], that is 56800235583 3769-12-05 11:13:03 +0800 CST to 3769-12-05 11:13:03 +0800 CST
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cron
Package cron implements a cron spec parser and job runner.
|
Package cron implements a cron spec parser and job runner. |
Package cmder exec cmd and catch the result.
|
Package cmder exec cmd and catch the result. |
errors is improved errors package.
|
errors is improved errors package. |
graceful package shutdown or reboot current process gracefully.
|
graceful package shutdown or reboot current process gracefully. |
inherit_net
Package inherit_net provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started.
|
Package inherit_net provides a family of Listen functions that either open a fresh connection or provide an inherited connection from when the process was started. |
internal
|
|
Package status is a handling status with code, msg, cause and stack.
|
Package status is a handling status with code, msg, cause and stack. |
Package versioning is a version comparison tool that conforms to semantic version 2.0.0
|
Package versioning is a version comparison tool that conforms to semantic version 2.0.0 |