util

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2019 License: Apache-2.0 Imports: 21 Imported by: 0

Documentation

Overview

Package util provides some utility tools for other components. Such as net-transporting, file-operating, rate-limiter.

Index

Constants

View Source
const (
	// RequestTag is the tag name for parsing structure to query parameters.
	// see function ParseQuery.
	RequestTag = "request"

	// DefaultTimeout is the default timeout to check connect.
	DefaultTimeout = 500 * time.Millisecond
)
View Source
const (
	ApplicationJSONUtf8Value = "application/json;charset=utf-8"
)

http content types

View Source
const BufferSize = 8 * 1024 * 1024

BufferSize define the buffer size when reading and writing file

Variables

View Source
var (
	// Printer is global StdPrinter.
	Printer = &StdPrinter{Out: os.Stdout}
)

Functions

func CheckConnect added in v0.3.0

func CheckConnect(ip string, port int, timeout int) (localIP string, e error)

CheckConnect checks the network connectivity between local and remote. param timeout: its unit is milliseconds, reset to 500 ms if <= 0 returns localIP

func ContainsString added in v0.3.0

func ContainsString(arr []string, value string) bool

ContainsString returns whether the value is in arr.

func CopyFile added in v0.3.0

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

CopyFile copies the file src to dst.

func CreateDirectory added in v0.3.0

func CreateDirectory(dirPath string) error

CreateDirectory creates directory recursively.

func DeleteFile added in v0.3.0

func DeleteFile(filePath string) error

DeleteFile deletes a file not a directory.

func DeleteFiles added in v0.3.0

func DeleteFiles(filePaths ...string)

DeleteFiles deletes all the given files.

func Do added in v0.3.0

func Do(url string, headers map[string]string, timeout time.Duration) (string, error)

Do performs the given http request and fills the given http response. When timeout <= 0, it will block until receiving response from server.

func ExtractHost added in v0.3.1

func ExtractHost(hostAndPort string) string

ExtractHost extracts host ip from the giving string.

func Get added in v0.3.0

func Get(url string, timeout time.Duration) (int, []byte, error)

Get sends a GET request to server. When timeout <= 0, it will block until receiving response from server.

func GetIPAndPortFromNode added in v0.3.1

func GetIPAndPortFromNode(node string, defaultPort int) (string, int)

GetIPAndPortFromNode return ip and port by parsing the node value. It will return defaultPort as the value of port when the node is a string without port or with an illegal port.

func HTTPGetWithHeaders added in v0.3.0

func HTTPGetWithHeaders(url string, headers map[string]string) (*http.Response, error)

HTTPGetWithHeaders send an HTTP GET request with headers.

func HTTPStatusOk added in v0.3.0

func HTTPStatusOk(code int) bool

HTTPStatusOk reports whether the http response code is 200.

func IsDir added in v0.3.0

func IsDir(name string) bool

IsDir reports whether the path is a directory.

func IsEmptyStr

func IsEmptyStr(s string) bool

IsEmptyStr returns whether the string x is empty.

func IsNil

func IsNil(value interface{}) (result bool)

IsNil returns whether the value is nil.

func IsRegularFile added in v0.3.0

func IsRegularFile(name string) bool

IsRegularFile reports whether the file is a regular file. If the given file is a symbol link, it will follow the link.

func JSONString added in v0.3.0

func JSONString(v interface{}) string

JSONString returns json string of the v.

func Link(src string, linkName string) error

Link creates a hard link pointing to src named linkName for a file.

func Max

func Max(x, y int32) int32

Max returns the larger of x or y.

func Md5Sum added in v0.3.0

func Md5Sum(name string) string

Md5Sum generate md5 for a given file

func Min

func Min(x, y int32) int32

Min returns the smaller of x or y.

func MoveFile added in v0.3.0

func MoveFile(src string, dst string) error

MoveFile moves the file src to dst.

func MoveFileAfterCheckMd5 added in v0.3.0

func MoveFileAfterCheckMd5(src string, dst string, md5 string) error

MoveFileAfterCheckMd5 will check whether the file's md5 is equals to the param md5 before move the file src to dst.

func OpenFile added in v0.3.0

func OpenFile(path string, flag int, perm os.FileMode) (*os.File, error)

OpenFile open a file. If the parent directory of the file isn't exist, it will create the directory.

func ParseQuery added in v0.3.0

func ParseQuery(query interface{}) string

ParseQuery only parses the fields with tag 'request' of the query to parameters. query must be a pointer to a struct.

func PathExist added in v0.3.0

func PathExist(name string) bool

PathExist reports whether the path is exist. Any error get from os.Stat, it will return false.

func PostJSON added in v0.3.0

func PostJSON(url string, body interface{}, timeout time.Duration) (int, []byte, error)

PostJSON send a POST request whose content-type is 'application/json;charset=utf-8'.

func Shuffle added in v0.3.0

func Shuffle(n int, swap func(int, int))

Shuffle pseudo-randomizes the order of elements. n is the number of elements. swap swaps the elements with indexes i and j. copy from rand.Shuffle of go1.10.

func TransRate added in v0.3.0

func TransRate(rate int) int32

TransRate trans the rate to multiples of 1000 For NewRateLimiter, the production of rate should be division by 1000.

Types

type LimitReader added in v0.3.0

type LimitReader struct {
	Src     io.Reader
	Limiter *RateLimiter
	// contains filtered or unexported fields
}

LimitReader read stream with RateLimiter.

func NewLimitReader added in v0.3.0

func NewLimitReader(src io.Reader, rate int, calculateMd5 bool) *LimitReader

NewLimitReader create LimitReader src: reader rate: bytes/second

func NewLimitReaderWithLimiter added in v0.3.0

func NewLimitReaderWithLimiter(rateLimiter *RateLimiter, src io.Reader, calculateMd5 bool) *LimitReader

NewLimitReaderWithLimiter create LimitReader with a rateLimiter. src: reader rate: bytes/second

func (*LimitReader) Md5 added in v0.3.0

func (lr *LimitReader) Md5() string

Md5 calculate the md5 of all contents read

func (*LimitReader) Read added in v0.3.0

func (lr *LimitReader) Read(p []byte) (n int, err error)

type Queue added in v0.3.0

type Queue interface {
	// Put puts item into the queue and keeps blocking if the queue is full.
	// It will return immediately and do nothing if the item is nil.
	Put(item interface{})

	// PutTimeout puts item into the queue and waits for timeout if the queue is full.
	// If timeout <= 0, it will return false immediately when queue is full.
	// It will return immediately and do nothing if the item is nil.
	PutTimeout(item interface{}, timeout time.Duration) bool

	// Poll gets an item from the queue and keeps blocking if the queue is empty.
	Poll() interface{}

	// PollTimeout gets an item from the queue and waits for timeout if the queue is empty.
	// If timeout <= 0, it will return (nil, bool) immediately when queue is empty.
	PollTimeout(timeout time.Duration) (interface{}, bool)

	// Len returns the current size of the queue.
	Len() int
}

Queue blocking queue. The items putted into queue mustn't be nil.

func NewQueue added in v0.3.0

func NewQueue(capacity int) Queue

NewQueue creates a blocking queue. If capacity <= 0, the queue capacity is infinite.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter is used for limiting the rate of transporting.

func NewRateLimiter

func NewRateLimiter(rate int32, window int64) *RateLimiter

NewRateLimiter creates a RateLimiter instance. rate: how many tokens are generated per second. 0 represents that don't limit the rate. window: generating tokens interval (millisecond, [1,1000]). The production of rate and window should be division by 1000.

func (*RateLimiter) AcquireBlocking

func (rl *RateLimiter) AcquireBlocking(token int32) int32

AcquireBlocking acquires tokens. It will be blocking unit the bucket has enough required number of tokens.

func (*RateLimiter) AcquireNonBlocking

func (rl *RateLimiter) AcquireNonBlocking(token int32) int32

AcquireNonBlocking acquires tokens. It will return -1 immediately when there is no enough number of tokens.

func (*RateLimiter) SetRate

func (rl *RateLimiter) SetRate(rate int32)

SetRate sets rate of RateLimiter.

type SimpleHTTPClient added in v0.3.0

type SimpleHTTPClient interface {
	PostJSON(url string, body interface{}, timeout time.Duration) (code int, res []byte, e error)
	Get(url string, timeout time.Duration) (code int, res []byte, e error)
}

SimpleHTTPClient defines some http functions used frequently.

var DefaultHTTPClient SimpleHTTPClient = &defaultHTTPClient{}

DefaultHTTPClient is the default implementation of SimpleHTTPClient.

type StdPrinter

type StdPrinter struct {
	Out io.Writer
}

StdPrinter output info to console directly.

func (*StdPrinter) Printf

func (sp *StdPrinter) Printf(format string, a ...interface{})

Printf formats according to a format specifier.

func (*StdPrinter) Println

func (sp *StdPrinter) Println(msg string)

Println output info to console directly.

Jump to

Keyboard shortcuts

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