util

package
v0.0.0-...-9a10968 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2022 License: Apache-2.0 Imports: 48 Imported by: 0

Documentation

Overview

https://ericchiang.github.io/post/go-tls/

Index

Constants

View Source
const (
	BYTE     = 1.0
	KILOBYTE = 1024 * BYTE
	MEGABYTE = 1024 * KILOBYTE
	GIGABYTE = 1024 * MEGABYTE
	TERABYTE = 1024 * GIGABYTE
)

ByteSize unit definition

View Source
const (
	FieldsKey = "fields"
	TagsKey   = "tags"
)

Event metadata constants. These keys are used to identify metadata stored in an event.

View Source
const (
	Verb_GET    string = "GET"
	Verb_PUT    string = "PUT"
	Verb_POST   string = "POST"
	Verb_DELETE string = "DELETE"
	Verb_HEAD   string = "HEAD"
)
View Source
const ContentTypeForm = "application/x-www-form-urlencoded;charset=UTF-8"
View Source
const ContentTypeJson = "application/json;charset=utf-8"
View Source
const ContentTypeXml = "application/xml;charset=utf-8"

Variables

View Source
var (
	// ErrKeyNotFound indicates that the specified key was not found.
	ErrKeyNotFound = errors.New("key not found")
)

Functions

func AddTags

func AddTags(ms MapStr, tags []string) error

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 AutoGetAddress

func AutoGetAddress(addr string) string

AutoGetAddress get valid address to listen, if the specify port is not available, auto choose the next one

func ByteSize

func ByteSize(bytes uint64) string

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 BytesToInt64

func BytesToInt64(buf []byte) int64

func BytesToString

func BytesToString(bs []byte) string

func BytesToUint32

func BytesToUint32(b []byte) (v uint32)

BytesToUint32 convert bytes to uint32

func BytesToUint64

func BytesToUint64(b []byte) (v uint64)

BytesToUint64 convert bytes to type uint64

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

func CheckProcessExists(pid int) bool

CheckProcessExists check if the pid is running

func ClearInstanceLock

func ClearInstanceLock()

ClearInstanceLock remove the lock

func ContainStr

func ContainStr(s, substr string) bool

func ContainsAnyInArray

func ContainsAnyInArray(s string, v []string) bool

func Copy

func Copy(sourceStruct interface{}, pointToTarget interface{}) (err error)

source should be a struct, target should be a pointer to the struct

func CopyFile

func CopyFile(src, dst string) (w int64, err error)

CopyFile copy file from src to dst

func CreateCert

func CreateCert(template, parent *x509.Certificate, pub interface{}, parentPriv interface{}) (
	cert *x509.Certificate, certPEM []byte, err error)

func CreateFile

func CreateFile(dir string, name string) (string, error)

CreateFile create file

func DeepCopy

func DeepCopy(value interface{}) interface{}

DeepCopy return a deep copied object

func Expand

func Expand(value map[string]interface{}) map[string]interface{}

func ExpandPrefixed

func ExpandPrefixed(value map[string]interface{}, prefix string) map[string]interface{}

func ExpandPrefixedToResult

func ExpandPrefixedToResult(value map[string]interface{}, prefix string, result map[string]interface{})

func FileAppendContentWithByte

func FileAppendContentWithByte(file string, content []byte) (int, error)

FileAppendContentWithByte append bytes to the end of the file

func FileAppendNewLine

func FileAppendNewLine(file string, content string) (int, error)

FileAppendNewLine append new line to the end of the file

func FileAppendNewLineWithByte

func FileAppendNewLineWithByte(file string, content []byte) (int, error)

FileAppendNewLineWithByte append bytes and break line(\n) to the end of the file

func FileDelete

func FileDelete(file string) error

FileDelete delete file

func FileExists

func FileExists(path string) bool

FileExists check if the path are exists

func FileExtension

func FileExtension(file string) string

FileExtension extract file extension from file name

func FileGetContent

func FileGetContent(file string) ([]byte, error)

FileGetContent get string from text file

func FileMTime

func FileMTime(file string) (int64, error)

FileMTime get file modified time

func FilePutContent

func FilePutContent(file string, content string) (int, error)

FilePutContent put string to file

func FilePutContentWithByte

func FilePutContentWithByte(file string, content []byte) (int, error)

FilePutContentWithByte put string to file

func FileSize

func FileSize(file string) (int64, error)

FileSize get file size as how many bytes

func FilterDirName

func FilterDirName(name string) bool

FilterDirName guess the file or directory is or contains Go source files.

func FilterSpecialChar

func FilterSpecialChar(keyword string) string

func Flatten

func Flatten(value interface{}, ignoreNil bool) map[string]interface{}

func FlattenJSON

func FlattenJSON(value interface{}, ignoreNil bool) (m map[string]interface{})

func FlattenJSONString

func FlattenJSONString(nestedstr, prefix string, ignoreNil bool) (string, error)

func FlattenPrefixed

func FlattenPrefixed(value interface{}, prefix string, ignoreNil bool) map[string]interface{}

func FlattenPrefixedToResult

func FlattenPrefixedToResult(value interface{}, prefix string, m map[string]interface{}, ignoreNil bool)

func FlattenPrefixedToResultWithTagAsFieldName

func FlattenPrefixedToResultWithTagAsFieldName(value interface{}, prefix string, m map[string]interface{}, tag string, ignoreNil bool)

func FormatTime

func FormatTime(date time.Time) string

func FormatTimeForFileName

func FormatTimeForFileName(date time.Time) string

func FormatTimeWithLocalTZ

func FormatTimeWithLocalTZ(date time.Time) string

func FormatTimeWithTZ

func FormatTimeWithTZ(date time.Time) string

func FormatUnixTimestamp

func FormatUnixTimestamp(unix int64) string

func FromJSONBytes

func FromJSONBytes(b []byte, v interface{})

FromJSONBytes simply do json unmarshal

func FromJson

func FromJson(str string, to interface{}) error

func FromUnixTimestamp

func FromUnixTimestamp(unix int64) time.Time

func GetAddress

func GetAddress(adr string) *net.TCPAddr

func GetAvailablePort

func GetAvailablePort(ip string, port int) int

GetAvailablePort get valid port to listen, if the specify port is not available, auto choose the next one

func GetCertTemplate

func GetCertTemplate() (*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 *rsa.PrivateKey) (clientTLSCert tls.Certificate, clientCertPEM, clientKeyPEM []byte)

func GetFieldValueByTagName

func GetFieldValueByTagName(any interface{}, tagName string, tagValue string) string

GetFieldValueByTagName return the field value which field was tagged with this tagName, only support string field

func GetHost

func GetHost(url string) string

GetHost return the host from a url

func GetIncrementID

func GetIncrementID(bucket string) int64

GetIncrementID return incremented id in specify bucket

func GetIntValue

func GetIntValue(any interface{}) int

func GetIntranetIP

func GetIntranetIP() (string, error)

func GetLocalZone

func GetLocalZone() string

GetLocalZone return a local timezone

func GetRootCert

func GetRootCert() (rootCert *x509.Certificate, rootKey *rsa.PrivateKey, rootCertPEM []byte)

func GetRootUrl

func GetRootUrl(source *uri.URL) string

GetRootUrl parse to get url root

func GetRuntimeErrorMessage

func GetRuntimeErrorMessage(r runtime.Error) string

func GetSafetyInternalAddress

func GetSafetyInternalAddress(addr string) string

func GetTypeName

func GetTypeName(any interface{}, lowercase bool) string

func GetUUID

func GetUUID() string

GetUUID return a generated uuid

func GetValidAddress

func GetValidAddress(addr string) string

GetValidAddress get valid address, input: :8001 -> output: 127.0.0.1:8001

func Int64ToBytes

func Int64ToBytes(i int64) []byte

func IntToString

func IntToString(num int) string

func Invoke

func Invoke(any interface{}, name string, args ...interface{})

Invoke dynamic execute function via function name and parameters

func IsExist

func IsExist(path string) bool

IsExist returns whether a file or directory exists.

func IsFile

func IsFile(file string) bool

IsFile returns false when it's a directory or does not exist.

func IsPublicIP

func IsPublicIP(IP net.IP) bool

func IsValidTLD

func IsValidTLD(tld string) bool

IsValidTLD returns true if tld is a valid tld, eg: com

func JoinPath

func JoinPath(filenames ...string) string

JoinPath return joined file path

func MD5digest

func MD5digest(str string) string

func MergeFields

func MergeFields(ms, fields MapStr, underRoot bool) error

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 MergeSpace

func MergeSpace(in string) (out string)

Removes all unnecessary whitespaces

func NoWordBreak

func NoWordBreak(in string) string

func PickRandomName

func PickRandomName() string

PickRandomName return a random name

func Post

func Post(url string, values url.Values) []byte

Post http post with a list of values

func PrefixStr

func PrefixStr(s, substr string) bool

func RegexStr

func RegexStr(s, regex string) bool

func RemoveSpaces

func RemoveSpaces(str string) string

func Rename

func Rename(file string, to string) error

Rename handle file rename

func ReplaceByte

func ReplaceByte(str []byte, old, new []byte) []byte

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 Sha1Hash

func Sha1Hash(str string) string

func SnapshotPersistID

func SnapshotPersistID()

SnapshotPersistID will make a snapshot and persist id stats to disk

func StringToUTF16

func StringToUTF16(s string) []uint16

func SubString

func SubString(str string, begin, length int) (substr string)

func SubStringWithSuffix

func SubStringWithSuffix(str string, length int, suffix string) string

func SuffixStr

func SuffixStr(s, substr string) bool

func TestListenPort

func TestListenPort(ip string, port int) bool

TestListenPort check availability of port with ip

func TestPort

func TestPort(port int) bool

TestPort check port availability

func ToBytes

func ToBytes(s string) (uint64, error)

ToBytes parses a string formatted by ByteSize as bytes.

func ToInt

func ToInt(str string) (int, error)

func ToJSONBytes

func ToJSONBytes(v interface{}) []byte

ToJSONBytes convert interface to json with byte array

func ToJson

func ToJson(in interface{}, indent bool) string

func ToLowercase

func ToLowercase(str []byte) []byte

ToLowercase convert string bytes to lowercase

func ToMegabytes

func ToMegabytes(s string) (uint64, error)

ToMegabytes parses a string formatted by ByteSize as megabytes.

func ToUppercase

func ToUppercase(str []byte) []byte

ToUppercase convert string bytes to uppercase

func TrimLeftStr

func TrimLeftStr(str string, left string) string

func TrimSpaces

func TrimSpaces(str string) string

TrimSpaces will trim space and line break

func TypeIsMap

func TypeIsMap(any interface{}) bool

func Uint32toBytes

func Uint32toBytes(b []byte, v uint32)

Uint32toBytes convert uint32 to bytes, max uint: 4294967295

func Uint64toBytes

func Uint64toBytes(b []byte, v uint64)

Uint64toBytes convert uint64 to bytes

func UnicodeIndex

func UnicodeIndex(str, substr string) int

func UrlDecode

func UrlDecode(str string) string

func UrlEncode

func UrlEncode(str string) string

func WaitServerUp

func WaitServerUp(addr string, duration time.Duration) error

func XSSHandle

func XSSHandle(src string) string

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 Backoff

type Backoff struct {
	Type     BackoffType
	Interval time.Duration
	// contains filtered or unexported fields
}

type BackoffType

type BackoffType int32
const (
	LINEAR BackoffType = iota
	EXP
)

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 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

func MapStrUnion(dict1 MapStr, dict2 MapStr) MapStr

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

func (m MapStr) Clone() MapStr

Clone returns a copy of the MapStr. It recursively makes copies of inner maps.

func (MapStr) CopyFieldsTo

func (m MapStr) CopyFieldsTo(to MapStr, key string) error

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) Delete

func (m MapStr) Delete(key string) error

Delete deletes the given key from the map.

func (MapStr) GetValue

func (m MapStr) GetValue(key string) (interface{}, error)

GetValue gets a value from the map. If the key does not exist then an error is returned.

func (MapStr) HasKey

func (m MapStr) HasKey(key string) (bool, error)

HasKey returns true if the key exist. If an error occurs then false is returned with a non-nil error.

func (MapStr) Put

func (m MapStr) Put(key string, value interface{}) (interface{}, error)

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) String

func (m MapStr) String() string

String returns the MapStr as JSON.

func (MapStr) StringToPrint

func (m MapStr) StringToPrint() string

StringToPrint returns the MapStr as pretty JSON.

func (MapStr) Update

func (m MapStr) Update(d MapStr)

Update copies all the key-value pairs from d to this map. If the key already exists then it is overwritten. This method does not merge nested maps.

type ReqLog

type ReqLog struct {
	Id     string    `json:"id,omitempty"`
	Name   string    `json:"name:omitempty"`
	Time   time.Time `json:"time,omitempty"`
	Type   string    `json:"type,omitempty"`
	Url    string    `json:"url,omitempty"`
	Method string    `json:"method,omitempty"`
	Body   string    `json:"body,omitempty"`
	Size   int       `json:"bodySize,omitempty"`
}

type Request

type Request struct {
	Agent   string
	Method  string
	Url     string
	Cookie  string
	Proxy   string
	Body    []byte
	StrBody string

	ContentType string
	// contains filtered or unexported fields
}

func NewDeleteRequest

func NewDeleteRequest(url string, body []byte) *Request

NewDeleteRequest issue a simple http delete request

func NewGetRequest

func NewGetRequest(url string, body []byte) *Request

NewGetRequest issue a simple http get request

func NewPostRequest

func NewPostRequest(url string, body []byte) *Request

NewPostRequest issue a simple http post request

func NewPutRequest

func NewPutRequest(url string, body []byte) *Request

NewPutRequest issue a simple http put request

func NewRequest

func NewRequest(method, url string) *Request

func (*Request) AcceptGzip

func (r *Request) AcceptGzip() *Request

func (*Request) AddHeader

func (r *Request) AddHeader(key, v string) *Request

func (*Request) Log

func (r *Request) Log() string

func (*Request) SetAgent

func (r *Request) SetAgent(agent string) *Request

func (*Request) SetBasicAuth

func (r *Request) SetBasicAuth(username, password string) *Request

SetBasicAuth set user and password for request

func (*Request) SetContentType

func (r *Request) SetContentType(contentType string) *Request

func (*Request) SetProxy

func (r *Request) SetProxy(proxy string) *Request

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

func ExecuteRequest(req *Request) (result *Result, err error)

ExecuteRequest issue a request

func ExecuteRequestWithContext

func ExecuteRequestWithContext(req *Request, context context.Context) (result *Result, err error)

ExecuteRequestWithContext issue a request with context

func HttpDelete

func HttpDelete(resource string) (*Result, error)

HttpDelete issue a simple http delete request

func HttpGet

func HttpGet(resource string) (*Result, error)

HttpGet issue a simple http get request

func HttpGetWithCookie

func HttpGetWithCookie(resource string, cookie string, proxy string) (*Result, error)

HttpGetWithCookie issue http request with cookie

func (*Result) Log

func (r *Result) Log(requestId string) string

type ResultLog

type ResultLog struct {
	Id        string    `json:"id,omitempty"`
	Name      string    `json:"name,omitempty"`
	RequestId string    `json:"req_id,omitempty"`
	Time      time.Time `json:"time,omitempty"`
	Type      string    `json:"type,omitempty"`
	Status    int       `json:"status,omitempty"`
	Url       string    `json:"url,omitempty"`
	Body      string    `json:"body,omitempty"`
	Size      uint64    `json:"bodySize,omitempty"`
}

type StringSet

type StringSet map[string]struct{}

func MakeStringSet

func MakeStringSet(strings ...string) StringSet

func (StringSet) Add

func (set StringSet) Add(s string)

func (StringSet) Count

func (set StringSet) Count() int

func (StringSet) Del

func (set StringSet) Del(s string)

func (StringSet) Has

func (set StringSet) Has(s string) (exists bool)

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");

Jump to

Keyboard shortcuts

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