Documentation ¶
Overview ¶
Index ¶
- Constants
- Variables
- func AbsInt(x int) int
- func AbsInt64(x int64) int64
- func AcquireTimer(timeout time.Duration) *time.Timer
- func AddTags(ms MapStr, tags []string) error
- func AddTagsWithKey(ms MapStr, key string, tags []string) error
- func AesGcmDecrypt(hexEncodedBytes, secret, hexEncodedSalt []byte) ([]byte, error)
- func AesGcmEncrypt(plaintext, secret []byte) ([]byte, []byte, error)
- func AtomicFileRename(sourceFile, targetFile string) error
- func AutoGetAddress(addr string) string
- func ByteSize(bytes uint64) string
- func BytesHasPrefix(data, prefix []byte) bool
- func BytesHasSuffix(left, right []byte) bool
- func BytesSearchValue(data, startTerm, endTerm, searchTrim []byte) bool
- func BytesToInt(buf []byte) int
- func BytesToInt64(buf []byte) int64
- func BytesToUint32(b []byte) (v uint32)
- func BytesToUint64(b []byte) (v uint64)
- func CheckIPBinding(ip string) (bool, error)
- func CheckInstanceLock(p string)
- func CheckProcessExists(pid int) bool
- func ClearAllID()
- func ClearInstanceLock()
- func ClientIP(r *http.Request) string
- func CompareInteger(x interface{}, y interface{}) bool
- func CompareStringAndBytes(b []byte, s string) bool
- func ContainStr(s, substr string) bool
- func ContainTags(tag string, tags string) bool
- func ContainsAnyInAnyIntArray(i interface{}, v []interface{}) bool
- func ContainsAnyInArray(s string, v []string) bool
- func ContainsInAnyInt32Array(i int, v []int) bool
- func ContainsInAnyIntArray(i int64, v []int64) bool
- func ConvertBytesFromString(formatedBytes string) (float64, error)
- func ConvertStringToMap(str string, splitter string) (k, v string, err error)
- func Copy(sourceStruct interface{}, pointToTarget interface{}) (err error)
- func CopyFile(src, dst string) (w int64, err error)
- func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}) (cert *x509.Certificate, certPEM []byte, err error)
- func CreateFile(dir string, name string) (string, error)
- func DeepCopy(value interface{}) interface{}
- func DiffTwoObject(a, b interface{}) (diff.Changelog, error)
- func EncodeToBytes(key interface{}) ([]byte, error)
- func EscapeNewLine(input []byte) []byte
- func Expand(value map[string]interface{}) map[string]interface{}
- func ExpandPrefixed(value map[string]interface{}, prefix string) map[string]interface{}
- func ExpandPrefixedToResult(value map[string]interface{}, prefix string, result map[string]interface{})
- func ExtractBool(unk interface{}) (bool, error)
- func ExtractFieldFromBytes(data *[]byte, start, end []byte, removedFromValue []byte) []byte
- func ExtractFieldFromBytesWitSkipBytes(data *[]byte, start, toBeSkipedBytes, end []byte, removedFromValue []byte) []byte
- func ExtractFieldFromJson(data *[]byte, fieldStartWith []byte, fieldEndWith []byte, ...) (bool, []byte)
- func ExtractFieldFromJsonOrder(data *[]byte, fieldStartWith []byte, fieldEndWith []byte, ...) (bool, []byte)
- func ExtractFloat(unk interface{}) (float64, error)
- func ExtractInt(unk interface{}) (int64, error)
- func ExtractString(unk interface{}) (string, error)
- func FileAppendContentWithByte(file string, content []byte) (int, error)
- func FileAppendNewLine(file string, content string) (int, error)
- func FileAppendNewLineWithByte(file string, content []byte) (int, error)
- func FileDelete(file string) error
- func FileExists(path string) bool
- func FileExtension(file string) string
- func FileGetContent(file string) ([]byte, error)
- func FileGetLines(filePath string) []string
- func FileLinesWalk(filePath string, f func([]byte)) error
- func FileMTime(file string) (int64, error)
- func FilePutContent(file string, content string) (int, error)
- func FilePutContentWithByte(file string, content []byte) (int, error)
- func FileSize(file string) (int64, error)
- func FilesExists(path ...string) bool
- func FilterDirName(name string) bool
- func FilterSpecialChar(keyword string) string
- func Flatten(value interface{}, ignoreNil bool) map[string]interface{}
- func FlattenJSON(value interface{}, ignoreNil bool) (m map[string]interface{})
- func FlattenJSONString(nestedstr, prefix string, ignoreNil bool) (string, error)
- func FlattenPrefixed(value interface{}, prefix string, ignoreNil bool) map[string]interface{}
- func FlattenPrefixedToResult(value interface{}, prefix string, m map[string]interface{}, ignoreNil bool)
- func FlattenPrefixedToResultWithTagAsFieldName(value interface{}, prefix string, m map[string]interface{}, tag string, ...)
- func FormatBytes(bytes float64, precision int) string
- func FormatNumber(input float64) string
- func FormatTime(date time.Time) string
- func FormatTimeForFileName(date time.Time) string
- func FormatTimeWithLocalTZ(date time.Time) string
- func FormatTimeWithTZ(date time.Time) string
- func FormatUnixTimestamp(unix int64) string
- func FromJSONBytes(b []byte, v interface{}) (err error)
- func FromJson(str string, to interface{}) error
- func FromUnixTimestamp(unix int64) time.Time
- func FromUnixTimestampInMicro(unix int64) time.Time
- func FromUnixTimestampInMilli(unix int64) time.Time
- func GenRsaKey() (prvkey, pubkey []byte)
- func GenerateRandomString(cnum int) string
- func GenerateServerCert(rootCert *x509.Certificate, rootKey *rsa.PrivateKey, rootCertPEM []byte, ...) (servCertPEM, servKeyPEM []byte, err error)
- func GetAddress(adr string) *net.TCPAddr
- func GetAvailablePort(ip string, port int) int
- func GetBytes(key interface{}) []byte
- func GetCertTemplate(dnsNames []string) (*x509.Certificate, error)
- func GetCertTemplateWithSingleDomain(dnsNames string) (*x509.Certificate, error)
- func GetClientCert(rootCert *x509.Certificate, rootKey any) (clientTLSCert tls.Certificate, clientCertPEM, clientKeyPEM []byte)
- func GetDurationOrDefault(str string, defaultV time.Duration) time.Duration
- func GetFieldAndTags(any interface{}, tags []string) []map[string]string
- func GetFieldValueByTagName(any interface{}, tagName string, tagValue string) string
- func GetHost(url string) string
- func GetHostName() string
- func GetIPPrefix(ip string) string
- func GetIncrementID(bucket string) uint32
- func GetIncrementID64(bucket string) uint64
- func GetInt64Value(any interface{}) int64
- func GetIntMapKeys(m map[int]int) []int
- func GetIntranetIP() (string, error)
- func GetLocalIPs() []string
- func GetLocalZone() string
- func GetLowPrecisionCurrentTime() time.Time
- func GetMapKeys(m map[string]KV) []string
- func GetMapValueByKeys(keys []string, m map[string]interface{}) (interface{}, bool)
- func GetPublishNetworkDeviceInfo(pattern string) (dev string, ip string, mask string, err error)
- func GetRootCert() (rootCert *x509.Certificate, rootKey *rsa.PrivateKey, rootCertPEM []byte)
- func GetRootUrl(source *uri.URL) string
- func GetRuntimeErrorMessage(r runtime.Error) string
- func GetSafetyInternalAddress(addr string) string
- func GetSkipHostnameVerifyFunc(pool *x509.CertPool) func([][]byte, [][]*x509.Certificate) error
- func GetSplitFunc(split []byte) func(data []byte, atEOF bool) (advance int, token []byte, err error)
- func GetStringIntMapKeys(m map[string]int) []string
- func GetSyncMapSize(m *sync.Map) int
- func GetTypeAndPackageName(any interface{}, lowercase bool) (string, string)
- func GetTypeName(any interface{}, lowercase bool) string
- func GetUUID() string
- func GetValidAddress(addr string) string
- func GetValueByKeys(keys []string, m MapStr) (interface{}, bool)
- func GzipCompress(a *[]byte, level int) []byte
- func GzipDecompress(data *[]byte) ([]byte, error)
- func HasSudoPermission() bool
- func InsertBytesAfterField(data *[]byte, start, toBeSkipedBytes, end []byte, bytesToInsert []byte) []byte
- func Int64ToBytes(i int64) []byte
- func Int64ToString(num int64) string
- func IntToBytes(n int) []byte
- func IntToString(num int) string
- func InterfaceToInt(y interface{}) int
- func Invoke(any interface{}, name string, args ...interface{})
- func Ipv4MaskString(m []byte) string
- func IsBytesEndingWith(data *[]byte, ending []byte) bool
- func IsBytesEndingWithOrder(data *[]byte, ending []byte, reverse bool) bool
- func IsExist(path string) bool
- func IsFile(file string) bool
- func IsFileWithinFolder(file, path string) bool
- func IsLocalAddress(address []string, localIPs []string) bool
- func IsPublicIP(IP net.IP) bool
- func IsRootUser() bool
- func IsValidEmail(email string) bool
- func IsValidTLD(tld string) bool
- func JoinArray(array []string, delimiter string) string
- func JoinInterfaceArray(array []interface{}, delimiter string, valueFunc func(str string) string) string
- func JoinMap(array map[string]interface{}, delimiter string) string
- func JoinMapInt(array map[string]int, delimiter string) string
- func JoinMapString(array map[string]string, delimiter string) string
- func JoinPath(filenames ...string) string
- func LimitedBytesSearch(data []byte, term []byte, limit int) bool
- func ListAllFiles(path string) ([]string, error)
- func MD5digest(str string) string
- func MD5digestBytes(b []byte) [16]byte
- func MD5digestString(b []byte) string
- func MapLength(m *sync.Map) int
- func MaxDuration(d1 time.Duration, d2 time.Duration) time.Duration
- func MaxInt64(x int64, y int64) int64
- func MergeFields(ms, fields MapStr, underRoot bool) error
- func MergeSpace(in string) (out string)
- func MinDuration(d1 time.Duration, d2 time.Duration) time.Duration
- func MinInt64(x int64, y int64) int64
- func Mod(data, max int) int
- func ModString(data string, max int) int
- func MustFromJSONBytes(b []byte, v interface{})
- func MustToJSON(v interface{}) string
- func MustToJSONBytes(v interface{}) []byte
- func NearestThousandFormat(num float64) string
- func NoWordBreak(in string) string
- func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string
- func ParseDuration(s string) (time.Duration, error)
- func ParsePrivateKey(der []byte) (any, error)
- func ParseStandardTime(value string) (time.Time, error)
- func ParseTime(str string) time.Time
- func PickRandomCnLegendName() string
- func PickRandomCnName() string
- func PickRandomName() string
- func PickRandomNameByDict(str string) string
- func PickRandomNumber(seed int) int
- func PidExists(pid int32) (bool, error)
- func Post(url string, values url.Values) []byte
- func PrefixAnyInArray(s string, v []string) bool
- func PrefixStr(s, substr string) bool
- func PrintStringByteLines(array [][]byte) string
- func ProcessJsonData(data *[]byte, blockSplit []byte, limitBlockSize int, ...) bool
- func PromptYesNo(prompt string, defaultAnswer bool) bool
- func RandomBytes(length int) ([]byte, error)
- func ReadInput() (string, error)
- func RegexPatternMatch(pattern, value string) bool
- func ReleaseTimer(t *time.Timer)
- func RemoveSpaces(str string) string
- func Rename(file string, to string) error
- func ReplaceByte(str []byte, old, new []byte) []byte
- func RestorePersistID(path string)
- func Round(num float64) int
- func RoundInt(input float64) int
- func RoundPrec(x float64, prec int) float64
- func RsaDecrypt(ciphertext, keyBytes []byte) []byte
- func RsaEncrypt(data, keyBytes []byte) []byte
- func RsaSignWithSha256(data []byte, keyBytes []byte) []byte
- func RsaVerySignWithSha256(data, signData, keyBytes []byte) bool
- func SetupTimeNowRefresh()
- func Sha1Hash(str string) string
- func Since(t1 time.Time) time.Duration
- func SnapshotPersistID()
- func StringArrayIntersection(arr1 []string, arr2 []string) []string
- func StringDefault(val, defaultV string) string
- func StringInArray(s []string, element string) bool
- func StringToFloat(s string) (float64, error)
- func StringToUTF16(s string) []uint16
- func StripCtlAndExtFromBytes(str string) string
- func StripCtlAndExtFromUTF8(str string) string
- func StripCtlAndExtFromUnicode(str string) string
- func StripCtlFromBytes(str string) string
- func StripCtlFromUTF8(str string) string
- func SubString(str string, begin, length int) (substr string)
- func SubStringWithSuffix(str string, length int, suffix string) string
- func SuffixAnyInArray(s string, v []string) bool
- func SuffixStr(s, substr string) bool
- func TestListenOnTCPPort(ip string, port int) bool
- func TestPort(port int) bool
- func TestTCPAddress(host string, timeout time.Duration) bool
- func TestTCPPort(host string, port int, duration time.Duration) bool
- func ToBytes(s string) (uint64, error)
- func ToFixed(num float64, precision int) float64
- func ToFloat(s string, defaultValue float64) float64
- func ToInt(str string) (int, error)
- func ToInt64(str string) (int64, error)
- func ToJSONBytes(v interface{}) ([]byte, error)
- func ToJson(in interface{}, indent bool) string
- func ToLowercase(str []byte) []byte
- func ToMegabytes(s string) (uint64, error)
- func ToString(obj interface{}) string
- func ToUppercase(str []byte) []byte
- func TrimLeftStr(str string, left string) string
- func TrimRightStr(str string, right string) string
- func TrimSpaces(str string) string
- func TryGetFileAbsPath(filePath string, ignoreMissing bool) string
- func TypeIsArray(any interface{}) bool
- func TypeIsMap(any interface{}) bool
- func Uint32toBytes(b []byte, v uint32)
- func Uint64toBytes(b []byte, v uint64)
- func UnicodeIndex(str, substr string) int
- func UnifyLocalAddress(host string) string
- func UnsafeBytesToString(bs []byte) string
- func UnsafeStringToBytes(s string) []byte
- func UrlDecode(str string) string
- func UrlEncode(str string) string
- func VersionCompare(v1, v2 string) (int, error)
- func WaitServerUp(addr string, duration time.Duration) error
- func WalkBytesAndReplace(data []byte, find, replace byte)
- func XSSHandle(src string) string
- func XXHash(data string) uint32
- type Annotation
- type AtomicID
- type ByteValue
- type Cache
- func (c *Cache) CleanUp() int
- func (c *Cache) Delete(k Key) Value
- func (c *Cache) Entries() map[Key]Value
- func (c *Cache) Get(k Key) Value
- func (c *Cache) Put(k Key, v Value) Value
- func (c *Cache) PutIfAbsent(k Key, v Value) Value
- func (c *Cache) PutIfAbsentWithTimeout(k Key, v Value, timeout time.Duration) Value
- func (c *Cache) PutWithTimeout(k Key, v Value, timeout time.Duration) Value
- func (c *Cache) Replace(k Key, v Value) Value
- func (c *Cache) ReplaceWithTimeout(k Key, v Value, timeout time.Duration) Value
- func (c *Cache) Size() int
- func (c *Cache) StartJanitor(interval time.Duration)
- func (c *Cache) StopJanitor()
- type Diff
- type DiffStatus
- type Diffs
- type EventMetadata
- type KV
- type Key
- type KeyValue
- type MapStr
- func (m MapStr) Clone() MapStr
- func (m MapStr) CopyFieldsTo(to MapStr, key string) error
- func (m MapStr) DeepUpdate(d MapStr)
- func (m MapStr) Delete(key string) error
- func (m MapStr) Equals(dst MapStr) bool
- func (m MapStr) Flatten() MapStr
- func (m MapStr) GetValue(key string) (interface{}, error)
- func (m MapStr) HasKey(key string) (bool, error)
- func (m *MapStr) Merge(vars map[string]interface{})
- func (m MapStr) Put(key string, value interface{}) (interface{}, error)
- func (m MapStr) SafetyHasKey(key string) bool
- func (m MapStr) String() string
- func (m MapStr) StringToPrint() string
- func (m MapStr) Update(d MapStr)
- type MapStrPointer
- type RawYaml
- type RawYamlList
- type RemovalListener
- type Request
- func (r *Request) AcceptGzip() *Request
- func (r *Request) AddHeader(key, v string) *Request
- func (r *Request) SetAgent(agent string) *Request
- func (r *Request) SetBasicAuth(username, password string) *Request
- func (r *Request) SetContentType(contentType string) *Request
- func (r *Request) SetProxy(proxy string) *Request
- type Result
- func ExecuteRequest(req *Request) (result *Result, err error)
- func ExecuteRequestWithCatchFlag(client *http.Client, req *Request, catchError bool) (result *Result, err error)
- func HttpDelete(resource string) (*Result, error)
- func HttpGet(resource string) (*Result, error)
- func HttpGetWithCookie(resource string, cookie string, proxy string) (*Result, error)
- type SQLQueryString
- type StringSet
- type Time
- type Value
- type Version
- func (v *Version) AtLeast(min *Version) bool
- func (v *Version) BuildMetadata() string
- func (v *Version) Compare(other string) (int, error)
- func (v *Version) Components() []uint
- func (v *Version) LessThan(other *Version) bool
- func (v *Version) Major() uint
- func (v *Version) Minor() uint
- func (v *Version) Patch() uint
- func (v *Version) PreRelease() string
- func (v *Version) String() string
- func (v *Version) WithBuildMetadata(buildMetadata string) *Version
- func (v *Version) WithMajor(major uint) *Version
- func (v *Version) WithMinor(minor uint) *Version
- func (v *Version) WithPatch(patch uint) *Version
- func (v *Version) WithPreRelease(preRelease string) *Version
Constants ¶
const ( BYTE = 1.0 KILOBYTE = 1024 * BYTE MEGABYTE = 1024 * KILOBYTE GIGABYTE = 1024 * MEGABYTE TERABYTE = 1024 * GIGABYTE )
ByteSize unit definition
const ( B float64 = 1 KB float64 = 1024 MB = 1024 * KB GB = 1024 * MB TB = 1024 * GB PB = 1024 * TB )
const ( FieldsKey = "fields" TagsKey = "tags" )
Event metadata constants. These keys are used to identify metadata stored in an event.
const ( Verb_GET string = "GET" Verb_PUT string = "PUT" Verb_POST string = "POST" Verb_DELETE string = "DELETE" Verb_HEAD string = "HEAD" )
const ContentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8"
const ContentTypeJson = "application/json;charset=utf-8"
const ContentTypeXml = "application/xml;charset=utf-8"
const LOCAL_ADDRESS = "127.0.0.1"
const TsLayout = "2006-01-02T15:04:05.000Z"
TsLayout is the layout to be used in the timestamp marshaling/unmarshaling everywhere. The timezone must always be UTC.
Variables ¶
var ( // ErrKeyNotFound indicates that the specified key was not found. ErrKeyNotFound = errors.New("key not found") )
var NEWLINE = byte('\n')
var PrometheusMetricReplacer = strings.NewReplacer(
".", "_",
"-", "_",
)
Prometheus metric name rule: [a-zA-Z_:][a-zA-Z0-9_:]* See https://prometheus.io/docs/concepts/data_model/
var SPACE = byte(' ')
Functions ¶
func AcquireTimer ¶
AcquireTimer returns a time.Timer from the pool and updates it to send the current time on its channel after at least timeout.
The returned Timer may be returned to the pool with ReleaseTimer when no longer needed. This allows reducing GC load.
func AddTags ¶
AddTags appends a tag to the tags field of ms. If the tags field does not exist then it will be created. If the tags field exists and is not a []string then an error will be returned. It does not deduplicate the list of tags.
func AddTagsWithKey ¶
AddTagsWithKey appends a tag to the key field of ms. If the field does not exist then it will be created. If the field exists and is not a []string then an error will be returned. It does not deduplicate the list.
func AesGcmDecrypt ¶
func AtomicFileRename ¶
func AutoGetAddress ¶
AutoGetAddress get valid address to listen, if the specify port is not available, auto choose the next one
func ByteSize ¶
ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth. The following units are available:
T: Terabyte G: Gigabyte M: Megabyte K: Kilobyte B: Byte
The unit that results in the smallest number greater than or equal to 1 is always chosen.
func BytesHasPrefix ¶
func BytesHasSuffix ¶
func BytesSearchValue ¶
func BytesToInt ¶
func BytesToInt64 ¶
func BytesToUint64 ¶
BytesToUint64 convert bytes to type uint64
func CheckIPBinding ¶
func CheckInstanceLock ¶
func CheckInstanceLock(p string)
CheckInstanceLock make sure there is not a lock placed before check, and place a lock after check
func CheckProcessExists ¶
CheckProcessExists check if the pid is running
func ClearAllID ¶
func ClearAllID()
func CompareInteger ¶
func CompareInteger(x interface{}, y interface{}) bool
func CompareStringAndBytes ¶
func ContainStr ¶
func ContainTags ¶
func ContainsAnyInAnyIntArray ¶
func ContainsAnyInAnyIntArray(i interface{}, v []interface{}) bool
func ContainsAnyInArray ¶
func ContainsInAnyInt32Array ¶
func ContainsInAnyIntArray ¶
func ConvertBytesFromString ¶
func ConvertStringToMap ¶
convert a->b to a,b
func Copy ¶
func Copy(sourceStruct interface{}, pointToTarget interface{}) (err error)
source should be a struct, target should be a pointer to the struct
func CreateCert ¶
func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}) ( cert *x509.Certificate, certPEM []byte, err error)
func DiffTwoObject ¶
func DiffTwoObject(a, b interface{}) (diff.Changelog, error)
func EncodeToBytes ¶
func ExpandPrefixed ¶
func ExpandPrefixedToResult ¶
func ExtractBool ¶
ExtractBool extracts a bool from an unknown type.
func ExtractFieldFromBytes ¶
func ExtractFieldFromJson ¶
func ExtractFloat ¶
ExtractFloat extracts a float from an unknown type.
func ExtractInt ¶
ExtractInt extracts an int from an unknown type.
func ExtractString ¶
ExtractString extracts a string from an unknown type.
func FileAppendContentWithByte ¶
FileAppendContentWithByte append bytes to the end of the file
func FileAppendNewLine ¶
FileAppendNewLine append new line to the end of the file
func FileAppendNewLineWithByte ¶
FileAppendNewLineWithByte append bytes and break line(\n) to the end of the file
func FileExtension ¶
FileExtension extract file extension from file name
func FileGetContent ¶
FileGetContent get string from text file
func FileGetLines ¶
func FileLinesWalk ¶
func FilePutContent ¶
FilePutContent put string to file
func FilePutContentWithByte ¶
FilePutContentWithByte put string to file
func FilesExists ¶
func FilterDirName ¶
FilterDirName guess the file or directory is or contains Go source files.
func FilterSpecialChar ¶
func FlattenJSON ¶
func FlattenJSONString ¶
func FlattenPrefixed ¶
func FlattenPrefixedToResult ¶
func FormatBytes ¶
func FormatNumber ¶
func FormatTime ¶
func FormatTimeForFileName ¶
func FormatTimeWithLocalTZ ¶
func FormatTimeWithTZ ¶
func FormatUnixTimestamp ¶
func FromJSONBytes ¶
func FromUnixTimestamp ¶
func GenerateRandomString ¶
func GenerateServerCert ¶
func GenerateServerCert(rootCert *x509.Certificate, rootKey *rsa.PrivateKey, rootCertPEM []byte, dnsNames []string) (servCertPEM, servKeyPEM []byte, err error)
func GetAddress ¶
func GetAvailablePort ¶
GetAvailablePort get valid port to listen, if the specify port is not available, auto choose the next one
func GetCertTemplate ¶
func GetCertTemplate(dnsNames []string) (*x509.Certificate, error)
func GetCertTemplateWithSingleDomain ¶
func GetCertTemplateWithSingleDomain(dnsNames string) (*x509.Certificate, error)
helper function to create a cert template with a serial number and other required fields
func GetClientCert ¶
func GetClientCert(rootCert *x509.Certificate, rootKey any) (clientTLSCert tls.Certificate, clientCertPEM, clientKeyPEM []byte)
func GetDurationOrDefault ¶
func GetFieldAndTags ¶
return field and tags, field name is using key: NAME
func GetFieldValueByTagName ¶
GetFieldValueByTagName returns the field value which field was tagged with the specified tagName, only supporting string fields.
func GetHostName ¶
func GetHostName() string
func GetIPPrefix ¶
func GetIncrementID ¶
func GetIncrementID64 ¶
func GetInt64Value ¶
func GetInt64Value(any interface{}) int64
func GetIntMapKeys ¶
func GetIntranetIP ¶
func GetLocalIPs ¶
func GetLocalIPs() []string
GetLocalIP returns the non loopback local IP of the host
func GetMapKeys ¶
func GetMapValueByKeys ¶
func GetRootCert ¶
func GetRootCert() (rootCert *x509.Certificate, rootKey *rsa.PrivateKey, rootCertPEM []byte)
func GetRuntimeErrorMessage ¶
func GetSplitFunc ¶
func GetStringIntMapKeys ¶
func GetSyncMapSize ¶
func GetTypeAndPackageName ¶
func GetTypeName ¶
func GetValidAddress ¶
GetValidAddress get valid address, input: :8001 -> output: 127.0.0.1:8001
func GetValueByKeys ¶
func GzipDecompress ¶
func HasSudoPermission ¶
func HasSudoPermission() bool
func InsertBytesAfterField ¶
func Int64ToBytes ¶
func Int64ToString ¶
func IntToBytes ¶
func IntToString ¶
func InterfaceToInt ¶
func InterfaceToInt(y interface{}) int
func Invoke ¶
func Invoke(any interface{}, name string, args ...interface{})
Invoke dynamic execute function via function name and parameters
func Ipv4MaskString ¶
func IsBytesEndingWith ¶
func IsBytesEndingWithOrder ¶
func IsFileWithinFolder ¶
func IsLocalAddress ¶
IsLocalAddress check if the address is local address
func IsPublicIP ¶
func IsRootUser ¶
func IsRootUser() bool
func IsValidEmail ¶
func IsValidTLD ¶
IsValidTLD returns true if tld is a valid tld, eg: com
func JoinInterfaceArray ¶
func ListAllFiles ¶
func MD5digestBytes ¶
func MD5digestString ¶
func MergeFields ¶
MergeFields merges the top-level keys and values in each source map (it does not perform a deep merge). If the same key exists in both, the value in fields takes precedence. If underRoot is true then the contents of the fields MapStr is merged with the value of the 'fields' key in ms.
An error is returned if underRoot is true and the value of ms.fields is not a MapStr.
func MustFromJSONBytes ¶
func MustFromJSONBytes(b []byte, v interface{})
MustFromJSONBytes simply do json unmarshal
func MustToJSON ¶
func MustToJSON(v interface{}) string
func MustToJSONBytes ¶
func MustToJSONBytes(v interface{}) []byte
func NearestThousandFormat ¶
fmt.Println(num, " = ", NearestThousandFormat(float64(num)))
10 = 10 100 = 100 1000 = 1.0k 10000 = 10.0k 3.12345678912e+09 = 3.1b 999.4 = 999 -372712 = -372.7k -37271922 = -37.2m -198 = -198
func NoWordBreak ¶
func NumberFormat ¶
func ParsePrivateKey ¶
func PickRandomCnLegendName ¶
func PickRandomCnLegendName() string
func PickRandomCnName ¶
func PickRandomCnName() string
func PickRandomName ¶
func PickRandomName() string
func PickRandomNameByDict ¶
func PickRandomNumber ¶
func PrefixAnyInArray ¶
func PrintStringByteLines ¶
func ProcessJsonData ¶
func ProcessJsonData(data *[]byte, blockSplit []byte, limitBlockSize int, validBlockMustContain [][]byte, reverse bool, matchBlockStartWith []byte, matchBlocksEndWith []byte, maxSpan int, matchedBlockProcessHandler func(matchedData []byte, globalStartOffset, globalEndOffset int)) bool
[]byte("gte"), []byte("strict_date_optional_time"), []byte("range") blockSplit 按照那个部分来进行划分多个区块; validBlockMustContain 区块必须包含的关键字 reverse 是从区块的前面还是后面进行处理 processBlockStartWithBlock 从什么地方开始处理 processBlockEndWithBlock 从什么地方结束处理 maxSpan 开始和结束位置的最大间隔,约束范围 匹配位置的处理函数
func PromptYesNo ¶
PromptYesNo Returns true if the user has entered Y or YES, capitalization is ignored, we are matching elasticsearch behavior
func RandomBytes ¶
func RegexPatternMatch ¶
func ReleaseTimer ¶
ReleaseTimer returns the time.Timer acquired via AcquireTimer to the pool and prevents the Timer from firing.
Do not access the released time.Timer or read from it's channel otherwise data races may occur.
func RemoveSpaces ¶
func ReplaceByte ¶
TODO optimize performance ReplaceByte simply replace old bytes to new bytes, the two bytes should have same length
func RestorePersistID ¶
func RestorePersistID(path string)
RestorePersistID will take the snapshot and restore to id seeds
func RoundPrec ¶
credit to https://github.com/DeyV/gotools/blob/master/numbers.go
func SetupTimeNowRefresh ¶
func SetupTimeNowRefresh()
func SnapshotPersistID ¶
func SnapshotPersistID()
SnapshotPersistID will make a snapshot and persist id stats to disk
func StringArrayIntersection ¶
func StringDefault ¶
func StringInArray ¶
func StringToFloat ¶
StringToFloat converts a string to a float64 Returns an error if the conversion is not possible
func StringToUTF16 ¶
func StripCtlAndExtFromBytes ¶
func StripCtlAndExtFromUTF8 ¶
func StripCtlAndExtFromUnicode ¶
Advanced Unicode normalization and filtering, see http://blog.golang.org/normalization and http://godoc.org/golang.org/x/text/unicode/norm for more details.
func StripCtlFromBytes ¶
two byte-oriented functions identical except for operator comparing c to 127.
func StripCtlFromUTF8 ¶
two UTF-8 functions identical except for operator comparing c to 127
func SuffixAnyInArray ¶
func TestListenOnTCPPort ¶
TestListenOnTCPPort check availability of port with ip
func ToJSONBytes ¶
func ToLowercase ¶
ToLowercase convert string bytes to lowercase
func ToMegabytes ¶
ToMegabytes parses a string formatted by ByteSize as megabytes.
func ToUppercase ¶
ToUppercase convert string bytes to uppercase
func TrimLeftStr ¶
func TrimRightStr ¶
func TryGetFileAbsPath ¶
Smart get file abs path
func TypeIsArray ¶
func TypeIsArray(any interface{}) bool
func Uint32toBytes ¶
Uint32toBytes convert uint32 to bytes, max uint: 4294967295
func UnicodeIndex ¶
func UnifyLocalAddress ¶
func UnsafeBytesToString ¶
func UnsafeStringToBytes ¶
func VersionCompare ¶
func WalkBytesAndReplace ¶
Types ¶
type Annotation ¶
type Annotation struct { Field string `json:"field,omitempty"` Type string `json:"type,omitempty"` Tag string `json:"tag,omitempty"` Annotation []Annotation `json:"annotation,omitempty"` }
func GetTagsByTagName ¶
func GetTagsByTagName(any interface{}, tagName string) []Annotation
type AtomicID ¶
type AtomicID struct { Sequence uint32 MaxSequence uint32 Sequence64 uint64 MaxSequence64 uint64 // contains filtered or unexported fields }
func GetAutoIncrement32ID ¶
func GetAutoIncrement64ID ¶
func (*AtomicID) Increment64 ¶
type Cache ¶
Cache is a semi-persistent mapping of keys to values. Elements added to the cache are store until they are explicitly deleted or are expired due time- based eviction based on last access time.
Expired elements are not visible through classes methods, but they do remain stored in the cache until CleanUp() is invoked. Therefore CleanUp() must be invoked periodically to prevent the cache from becoming a memory leak. If you want to start a goroutine to perform periodic clean-up then see StartJanitor().
Cache does not support storing nil values. Any attempt to put nil into the cache will cause a panic.
func NewCache ¶
NewCache creates and returns a new Cache. d is the length of time after last access that cache elements expire. initialSize is the initial allocation size used for the Cache's underlying map.
func NewCacheWithExpireOnAdd ¶
NewCacheWithExpireOnAdd creates and returns a new Cache that does not updated the expiration time when the object is accessed. The expiration is only set when a new object is added to the cache and is not updated until it expires and re-inserted.
func NewCacheWithRemovalListener ¶
func NewCacheWithRemovalListener(d time.Duration, initialSize int, l RemovalListener) *Cache
NewCacheWithRemovalListener creates and returns a new Cache and register a RemovalListener callback function. d is the length of time after last access that cache elements expire. initialSize is the initial allocation size used for the Cache's underlying map. l is the callback function that will be invoked when cache elements are removed from the map on CleanUp.
func (*Cache) CleanUp ¶
CleanUp performs maintenance on the cache by removing expired elements from the cache. If a RemoveListener is registered it will be invoked for each element that is removed during this clean up operation. The RemovalListener is invoked on the caller's goroutine.
func (*Cache) Delete ¶
Delete a key from the map and return the value or nil if the key does not exist. The RemovalListener is not notified for explicit deletions.
func (*Cache) Get ¶
Get the current value associated with a key or nil if the key is not present. The last access time of the element is updated.
func (*Cache) Put ¶
Put writes the given key and value to the map replacing any existing value if it exists. The previous value associated with the key returned or nil if the key was not present.
func (*Cache) PutIfAbsent ¶
PutIfAbsent writes the given key and value to the cache only if the key is absent from the cache. Nil is returned if the key-value pair were written, otherwise the old value is returned.
func (*Cache) PutIfAbsentWithTimeout ¶
PutIfAbsentWithTimeout writes the given key and value to the cache only if the key is absent from the cache. Nil is returned if the key-value pair were written, otherwise the old value is returned. The cache expiration time will be overwritten by timeout of the key being inserted.
func (*Cache) PutWithTimeout ¶
PutWithTimeout writes the given key and value to the map replacing any existing value if it exists. The previous value associated with the key returned or nil if the key was not present. The cache expiration time will be overwritten by timeout of the key being inserted.
func (*Cache) Replace ¶
Replace overwrites the value for a key only if the key exists. The old value is returned if the value is updated, otherwise nil is returned.
func (*Cache) ReplaceWithTimeout ¶
ReplaceWithTimeout overwrites the value for a key only if the key exists. The old value is returned if the value is updated, otherwise nil is returned. The cache expiration time will be overwritten by timeout of the key being inserted.
func (*Cache) Size ¶
Size returns the number of elements in the cache. The number includes both active elements and expired elements that have not been cleaned up.
func (*Cache) StartJanitor ¶
StartJanitor starts a goroutine that will periodically invoke the cache's CleanUp() method.
func (*Cache) StopJanitor ¶
func (c *Cache) StopJanitor()
StopJanitor stops the goroutine created by StartJanitor.
type Diff ¶
type Diff struct { Diff string Yaml1Struct *RawYaml Yaml2Struct *RawYaml Status DiffStatus // contains filtered or unexported fields }
type DiffStatus ¶
type DiffStatus int
const ( DiffStatusExists DiffStatus = 1 DiffStatusSame DiffStatus = 2 DiffStatus1Missing DiffStatus = 3 DiffStatus2Missing DiffStatus = 4 )
type EventMetadata ¶
type EventMetadata struct { Fields MapStr FieldsUnderRoot bool `config:"fields_under_root"` Tags []string }
EventMetadata contains fields and tags that can be added to an event via configuration.
type KeyValue ¶
type KeyValue struct { Key string `json:"key,omitempty"` Value int64 `json:"value,omitempty"` Payload interface{} `json:"payload,omitempty"` }
func SortKeyValueArray ¶
sort by value desc by default
func SortMapStrIntToKV ¶
type MapStr ¶
type MapStr map[string]interface{}
MapStr is a map[string]interface{} wrapper with utility methods for common map operations like converting to JSON.
func MapStrUnion ¶
MapStrUnion creates a new MapStr containing the union of the key-value pairs of the two maps. If the same key is present in both, the key-value pairs from dict2 overwrite the ones from dict1.
func (MapStr) Clone ¶
Clone returns a copy of the MapStr. It recursively makes copies of inner maps.
func (MapStr) CopyFieldsTo ¶
CopyFieldsTo copies the field specified by key to the given map. It will overwrite the key if it exists. An error is returned if the key does not exist in the source map.
func (MapStr) DeepUpdate ¶
DeepUpdate recursively copies the key-value pairs from d to this map. If the key is present and a map as well, the sub-map will be updated recursively via DeepUpdate. DeepUpdateNoOverwrite is a version of this function that does not overwrite existing values.
func (MapStr) Flatten ¶
Flatten flattens the given MapStr and returns a flat MapStr.
Example:
"hello": MapStr{"world": "test" }
This is converted to:
"hello.world": "test"
This can be useful for testing or logging.
func (MapStr) GetValue ¶
GetValue gets a value from the map. If the key does not exist then an error is returned.
func (MapStr) Put ¶
Put associates the specified value with the specified key. If the map previously contained a mapping for the key, the old value is replaced and returned. The key can be expressed in dot-notation (e.g. x.y) to put a value into a nested map.
If you need insert keys containing dots then you must use bracket notation to insert values (e.g. m[key] = value).
func (MapStr) SafetyHasKey ¶
HasKey returns true if the key exist. If an error occurs then false is returned with a non-nil error.
func (MapStr) StringToPrint ¶
StringToPrint returns the MapStr as pretty JSON.
type MapStrPointer ¶
type MapStrPointer struct {
// contains filtered or unexported fields
}
MapStrPointer stores a pointer to atomically get/set a MapStr object This should give faster access for use cases with lots of reads and a few changes. It's important to note that modifying the map is not thread safe, only fully replacing it.
func NewMapStrPointer ¶
func NewMapStrPointer(m MapStr) MapStrPointer
NewMapStrPointer initializes and returns a pointer to the given MapStr
func (MapStrPointer) Get ¶
func (m MapStrPointer) Get() MapStr
Get returns the MapStr stored under this pointer
func (*MapStrPointer) Set ¶
func (m *MapStrPointer) Set(p MapStr)
Set stores a pointer the given MapStr, replacing any previous one
type RawYamlList ¶
type RawYamlList []*RawYaml
type RemovalListener ¶
RemovalListener is the callback function type that can be registered with the cache to receive notification of the removal of expired elements.
type Request ¶
type Request struct { Agent string Method string Path string Url string Cookie string Proxy string Body []byte ContentType string Compress bool Context context.Context // contains filtered or unexported fields }
func NewDeleteRequest ¶
NewDeleteRequest issue a simple http delete request
func NewGetRequest ¶
NewGetRequest issue a simple http get request
func NewPostRequest ¶
NewPostRequest issue a simple http post request
func NewPutRequest ¶
NewPutRequest issue a simple http put request
func NewRequest ¶
func (*Request) AcceptGzip ¶
func (*Request) SetBasicAuth ¶
SetBasicAuth set user and password for request
func (*Request) SetContentType ¶
type Result ¶
type Result struct { Host string Url string Headers map[string][]string Body []byte StatusCode int Size uint64 }
Result is the http request result
func ExecuteRequest ¶
ExecuteRequest issue a request
func HttpDelete ¶
HttpDelete issue a simple http delete request
type SQLQueryString ¶
type SQLQueryString struct {
// contains filtered or unexported fields
}
func NewSQLQueryString ¶
func NewSQLQueryString(query string) *SQLQueryString
func (SQLQueryString) AfterAll ¶
func (p SQLQueryString) AfterAll(word string) (atAfters []string)
func (SQLQueryString) TableNames ¶
func (p SQLQueryString) TableNames() (names []string, err error)
TableNames returns all table names of the SQL statement
type Time ¶
Time is an abstraction for the time.Time type
func MustParseTime ¶
MustParseTime is a convenience equivalent of the ParseTime function that panics in case of errors.
func ParseTimeWithStandardSpec ¶
ParseTime parses a time in the TsLayout format.
func (Time) MarshalJSON ¶
MarshalJSON implements json.Marshaler interface. The time is a quoted string in the JsTsLayout format.
func (*Time) UnmarshalJSON ¶
UnmarshalJSON implements js.Unmarshaler interface. The time is expected to be a quoted string in TsLayout format.
type Version ¶
type Version struct {
// contains filtered or unexported fields
}
Version is an opaque representation of a version number
func MustParseGeneric ¶
MustParseGeneric is like ParseGeneric except that it panics on error
func MustParseSemantic ¶
MustParseSemantic is like ParseSemantic except that it panics on error
func ParseGeneric ¶
ParseGeneric parses a "generic" version string. The version string must consist of two or more dot-separated numeric fields (the first of which can't have leading zeroes), followed by arbitrary uninterpreted data (which need not be separated from the final numeric field by punctuation). For convenience, leading and trailing whitespace is ignored, and the version can be preceded by the letter "v". See also ParseSemantic.
func ParseSemantic ¶
ParseSemantic parses a version string that exactly obeys the syntax and semantics of the "Semantic Versioning" specification (http://semver.org/) (although it ignores leading and trailing whitespace, and allows the version to be preceded by "v"). For version strings that are not guaranteed to obey the Semantic Versioning syntax, use ParseGeneric.
func (*Version) AtLeast ¶
AtLeast tests if a version is at least equal to a given minimum version. If both Versions are Semantic Versions, this will use the Semantic Version comparison algorithm. Otherwise, it will compare only the numeric components, with non-present components being considered "0" (ie, "1.4" is equal to "1.4.0").
func (*Version) BuildMetadata ¶
BuildMetadata returns the build metadata, if v is a Semantic Version, or ""
func (*Version) Compare ¶
Compare compares v against a version string (which will be parsed as either Semantic or non-Semantic depending on v). On success it returns -1 if v is less than other, 1 if it is greater than other, or 0 if they are equal.
func (*Version) Components ¶
Components returns the version number components
func (*Version) LessThan ¶
LessThan tests if a version is less than a given version. (It is exactly the opposite of AtLeast, for situations where asking "is v too old?" makes more sense than asking "is v new enough?".)
func (*Version) PreRelease ¶
PreRelease returns the prerelease metadata, if v is a Semantic Version, or ""
func (*Version) String ¶
String converts a Version back to a string; note that for versions parsed with ParseGeneric, this will not include the trailing uninterpreted portion of the version number.
func (*Version) WithBuildMetadata ¶
WithBuildMetadata returns copy of the version object with requested buildMetadata
func (*Version) WithMajor ¶
WithMajor returns copy of the version object with requested major number
func (*Version) WithMinor ¶
WithMinor returns copy of the version object with requested minor number
func (*Version) WithPatch ¶
WithPatch returns copy of the version object with requested patch number
func (*Version) WithPreRelease ¶
WithPreRelease returns copy of the version object with requested prerelease
Source Files ¶
- bytes.go
- bytes_unit.go
- cache.go
- certutil.go
- crypto.go
- decimal.go
- domain.go
- extractors.go
- flatten.go
- fsutils.go
- gzip.go
- host.go
- idutil.go
- instance.go
- instance_unix.go
- keyvalue.go
- mapstr.go
- mapstr_pointer.go
- math.go
- netutils.go
- numbers.go
- obj_diff.go
- permission_unix.go
- post.go
- random.go
- reflectutils.go
- rename.go
- sql_query.go
- string_replacer.go
- stringset.go
- stringutil.go
- strip.go
- sync.go
- terminal.go
- time.go
- timer.go
- version.go
- webhunter.go
- xxhash.go
- yaml_diff.go
Directories ¶
Path | Synopsis |
---|---|
Package file copied from github.com/elastic/beats https://github.com/elastic/beats/blob/master/LICENSE Licensed under the Apache License, Version 2.0 (the "License");
|
Package file copied from github.com/elastic/beats https://github.com/elastic/beats/blob/master/LICENSE Licensed under the Apache License, Version 2.0 (the "License"); |