Documentation ¶
Overview ¶
Package util provides some utility tools for other components. Such as net-transporting, file-operating, rate-limiter.
Index ¶
- Constants
- func Atime(stat *syscall.Stat_t) time.Time
- func AtimeSec(stat *syscall.Stat_t) int64
- func CheckConnect(ip string, port int, timeout int) (localIP string, e error)
- func ConstructRangeStr(rangeStr string) string
- func ConvertHeaders(headers []string) map[string]string
- func ConvertTimeIntToString(timestamp int64) (string, error)
- func ConvertTimeStringToInt(timeStr string) (int64, error)
- func CopyFile(src string, dst string) (err error)
- func CreateDirectory(dirPath string) error
- func Ctime(stat *syscall.Stat_t) time.Time
- func CtimeSec(stat *syscall.Stat_t) int64
- func DeleteFile(filePath string) error
- func DeleteFiles(filePaths ...string)
- func Do(url string, headers map[string]string, timeout time.Duration) (string, error)
- func ExtractHost(hostAndPort string) string
- func FilterURLParam(url string, filters []string) string
- func Get(url string, timeout time.Duration) (int, []byte, error)
- func GetAllIPs() (ipList []string, err error)
- func GetContentLength(url string, headers map[string]string) (int64, int, error)
- func GetIPAndPortFromNode(node string, defaultPort int) (string, int)
- func GetSys(info os.FileInfo) (*syscall.Stat_t, bool)
- func GetWithHeaders(url string, headers map[string]string, timeout time.Duration) (code int, resBody []byte, err error)
- func HTTPGet(url string, headers map[string]string) (*http.Response, error)
- func HTTPGetTimeout(url string, headers map[string]string, timeout time.Duration) (*http.Response, error)
- func HTTPStatusOk(code int) bool
- func HTTPWithHeaders(method, url string, headers map[string]string, timeout time.Duration) (*http.Response, error)
- func IsDir(name string) bool
- func IsEmptySlice(values []string) bool
- func IsEmptyStr(s string) bool
- func IsExpired(url string, headers map[string]string, lastModified int64, eTag string) (bool, error)
- func IsNatural(value string) bool
- func IsNil(value interface{}) (result bool)
- func IsNumeric(value string) bool
- func IsPositive(value int64) bool
- func IsRegularFile(name string) bool
- func IsSupportRange(url string, headers map[string]string) (bool, error)
- func IsTrue(value bool) bool
- func IsValidIP(ip string) bool
- func IsValidURL(url string) bool
- func JSONString(v interface{}) string
- func Link(src string, linkName string) error
- func LoadYaml(path string, out interface{}) error
- func Max(x, y int32) int32
- func Md5Sum(name string) string
- func Min(x, y int32) int32
- func MoveFile(src string, dst string) error
- func MoveFileAfterCheckMd5(src string, dst string, md5 string) error
- func NetLimit() string
- func OpenFile(path string, flag int, perm os.FileMode) (*os.File, error)
- func ParseQuery(query interface{}) string
- func PathExist(name string) bool
- func PostJSON(url string, body interface{}, timeout time.Duration) (int, []byte, error)
- func PostJSONWithHeaders(url string, headers map[string]string, body interface{}, timeout time.Duration) (int, []byte, error)
- func Sha1(contents []string) string
- func Sha256(value string) string
- func SubString(str string, start, end int) string
- func SymbolicLink(src string, target string) error
- func TransRate(rate int) int32
- type AtomicInt
- type LimitReader
- func NewLimitReader(src io.Reader, rate int, calculateMd5 bool) *LimitReader
- func NewLimitReaderWithLimiter(rateLimiter *RateLimiter, src io.Reader, calculateMd5 bool) *LimitReader
- func NewLimitReaderWithLimiterAndMD5Sum(src io.Reader, rateLimiter *RateLimiter, md5sum hash.Hash) *LimitReader
- func NewLimitReaderWithMD5Sum(src io.Reader, rate int, md5sum hash.Hash) *LimitReader
- type MockHTTPClient
- func (m *MockHTTPClient) CreateGetFunc(code int, res []byte, e error) getFunc
- func (m *MockHTTPClient) CreateGetWithHeadersFunc(code int, res []byte, e error) getWithHeadersFunc
- func (m *MockHTTPClient) CreatePostJSONFunc(code int, res []byte, e error) postJSONFunc
- func (m *MockHTTPClient) CreatePostJSONWithHeadersFunc(code int, res []byte, e error) postJSONWithHeadersFunc
- func (m *MockHTTPClient) Get(url string, timeout time.Duration) (int, []byte, error)
- func (m *MockHTTPClient) GetWithHeaders(url string, headers map[string]string, timeout time.Duration) (int, []byte, error)
- func (m *MockHTTPClient) PostJSON(url string, body interface{}, timeout time.Duration) (int, []byte, error)
- func (m *MockHTTPClient) PostJSONWithHeaders(url string, headers map[string]string, body interface{}, timeout time.Duration) (int, []byte, error)
- func (m *MockHTTPClient) Reset()
- type RangeStruct
- type RateLimiter
- type SimpleHTTPClient
- type SyncMap
- func (mmap *SyncMap) Add(key string, value interface{}) error
- func (mmap *SyncMap) Get(key string) (interface{}, error)
- func (mmap *SyncMap) GetAsAtomicInt(key string) (*AtomicInt, error)
- func (mmap *SyncMap) GetAsBitset(key string) (*bitset.BitSet, error)
- func (mmap *SyncMap) GetAsBool(key string) (bool, error)
- func (mmap *SyncMap) GetAsInt(key string) (int, error)
- func (mmap *SyncMap) GetAsMap(key string) (*SyncMap, error)
- func (mmap *SyncMap) GetAsString(key string) (string, error)
- func (mmap *SyncMap) ListKeyAsIntSlice() (result []int)
- func (mmap *SyncMap) ListKeyAsStringSlice() (result []string)
- func (mmap *SyncMap) Remove(key string) error
Constants ¶
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 )
const (
ApplicationJSONUtf8Value = "application/json;charset=utf-8"
)
http content types
const BufferSize = 8 * 1024 * 1024
BufferSize define the buffer size when reading and writing file
Variables ¶
This section is empty.
Functions ¶
func CheckConnect ¶
CheckConnect checks the network connectivity between local and remote. param timeout: its unit is milliseconds, reset to 500 ms if <= 0 returns localIP
func ConstructRangeStr ¶
ConstructRangeStr wrap the rangeStr as a HTTP Range header value.
func ConvertHeaders ¶
ConvertHeaders converts headers from array type to map type for http request.
func ConvertTimeIntToString ¶
ConvertTimeIntToString converts a int64 timestamp to a string time.
func ConvertTimeStringToInt ¶
ConvertTimeStringToInt converts a string time to a int64 timestamp.
func CreateDirectory ¶
CreateDirectory creates directory recursively.
func Do ¶
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 ¶
ExtractHost extracts host ip from the giving string.
func FilterURLParam ¶
FilterURLParam filters request queries in URL. Eg: If you pass parameters as follows:
url: http://a.b.com/locate?key1=value1&key2=value2&key3=value3 filter: key2
and then you will get the following value as the return:
http://a.b.com/locate?key1=value1&key3=value3
func Get ¶
Get sends a GET request to server. When timeout <= 0, it will block until receiving response from server.
func GetContentLength ¶
GetContentLength send a head request to get file length.
func GetIPAndPortFromNode ¶
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 GetWithHeaders ¶
func GetWithHeaders(url string, headers map[string]string, timeout time.Duration) (code int, resBody []byte, err error)
GetWithHeaders sends a GET request to server. When timeout <= 0, it will block until receiving response from server.
func HTTPGetTimeout ¶
func HTTPGetTimeout(url string, headers map[string]string, timeout time.Duration) (*http.Response, error)
HTTPGetTimeout send an HTTP GET request with timeout.
func HTTPStatusOk ¶
HTTPStatusOk reports whether the http response code is 200.
func HTTPWithHeaders ¶
func HTTPWithHeaders(method, url string, headers map[string]string, timeout time.Duration) (*http.Response, error)
HTTPWithHeaders send an HTTP request with headers and specified method.
func IsEmptySlice ¶
IsEmptySlice returns whether the slice values is empty.
func IsExpired ¶
func IsExpired(url string, headers map[string]string, lastModified int64, eTag string) (bool, error)
IsExpired checks if a resource received or stored is the same.
func IsNumeric ¶
IsNumeric returns whether the value is a numeric. If the bitSize of value below 0 or above 64 an error is returned.
func IsPositive ¶
IsPositive returns whether the value is a positive number.
func IsRegularFile ¶
IsRegularFile reports whether the file is a regular file. If the given file is a symbol link, it will follow the link.
func IsSupportRange ¶
IsSupportRange checks if the source url support partial requests.
func IsValidURL ¶
IsValidURL returns whether the string url is a valid HTTP URL.
func MoveFileAfterCheckMd5 ¶
MoveFileAfterCheckMd5 will check whether the file's md5 is equals to the param md5 before move the file src to dst.
func OpenFile ¶
OpenFile open a file. If the parent directory of the file isn't exist, it will create the directory.
func ParseQuery ¶
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 ¶
PathExist reports whether the path is exist. Any error get from os.Stat, it will return false.
func PostJSON ¶
PostJSON send a POST request whose content-type is 'application/json;charset=utf-8'.
func PostJSONWithHeaders ¶
func PostJSONWithHeaders(url string, headers map[string]string, body interface{}, timeout time.Duration) (int, []byte, error)
PostJSONWithHeaders send a POST request whose content-type is 'application/json;charset=utf-8'.
func SubString ¶
SubString returns the subString of {str} which begins at {start} and end at {end - 1}.
func SymbolicLink ¶
SymbolicLink creates target as a symbolic link to src.
Types ¶
type AtomicInt ¶
type AtomicInt struct {
// contains filtered or unexported fields
}
AtomicInt is a struct that can be added or subtracted atomically.
type LimitReader ¶
type LimitReader struct { Src io.Reader Limiter *RateLimiter // contains filtered or unexported fields }
LimitReader read stream with RateLimiter.
func NewLimitReader ¶
func NewLimitReader(src io.Reader, rate int, calculateMd5 bool) *LimitReader
NewLimitReader create LimitReader src: reader rate: bytes/second
func NewLimitReaderWithLimiter ¶
func NewLimitReaderWithLimiter(rateLimiter *RateLimiter, src io.Reader, calculateMd5 bool) *LimitReader
NewLimitReaderWithLimiter create LimitReader with a rateLimiter. src: reader rate: bytes/second
func NewLimitReaderWithLimiterAndMD5Sum ¶
func NewLimitReaderWithLimiterAndMD5Sum(src io.Reader, rateLimiter *RateLimiter, md5sum hash.Hash) *LimitReader
NewLimitReaderWithLimiterAndMD5Sum create LimitReader with rateLimiter and md5 sum. src: reader rate: bytes/second
func NewLimitReaderWithMD5Sum ¶
NewLimitReaderWithMD5Sum create LimitReader with a md5 sum. src: reader rate: bytes/second
func (*LimitReader) Md5 ¶
func (lr *LimitReader) Md5() string
Md5 calculate the md5 of all contents read
type MockHTTPClient ¶
type MockHTTPClient struct { PostJSONFunc postJSONFunc GetFunc getFunc PostJSONWithHeadersFunc postJSONWithHeadersFunc GetWithHeadersFunc getWithHeadersFunc }
MockHTTPClient fakes a customized implementation of util.SimpleHTTPClient.
func NewMockHTTPClient ¶
func NewMockHTTPClient() *MockHTTPClient
NewMockHTTPClient returns a new MockHTTPClient instance.
func (*MockHTTPClient) CreateGetFunc ¶
func (m *MockHTTPClient) CreateGetFunc(code int, res []byte, e error) getFunc
CreateGetFunc returns a mock getFunc func which will always return the specific results.
func (*MockHTTPClient) CreateGetWithHeadersFunc ¶
func (m *MockHTTPClient) CreateGetWithHeadersFunc(code int, res []byte, e error) getWithHeadersFunc
CreateGetWithHeadersFunc returns a mock getWithHeadersFunc func which will always return the specific results.
func (*MockHTTPClient) CreatePostJSONFunc ¶
func (m *MockHTTPClient) CreatePostJSONFunc(code int, res []byte, e error) postJSONFunc
CreatePostJSONFunc returns a mock postJSONFunc func which will always return the specific results.
func (*MockHTTPClient) CreatePostJSONWithHeadersFunc ¶
func (m *MockHTTPClient) CreatePostJSONWithHeadersFunc(code int, res []byte, e error) postJSONWithHeadersFunc
CreatePostJSONWithHeadersFunc returns a mock postJSONWithHeadersFunc func / which will always return the specific results.
func (*MockHTTPClient) GetWithHeaders ¶
func (m *MockHTTPClient) GetWithHeaders(url string, headers map[string]string, timeout time.Duration) ( int, []byte, error)
GetWithHeaders mocks base method.
func (*MockHTTPClient) PostJSON ¶
func (m *MockHTTPClient) PostJSON(url string, body interface{}, timeout time.Duration) ( int, []byte, error)
PostJSON mocks base method.
type RangeStruct ¶
RangeStruct contains the start and end of a http header range.
func GetRangeSE ¶
func GetRangeSE(rangeHTTPHeader string, length int64) ([]*RangeStruct, error)
GetRangeSE parses the start and the end from range HTTP header and returns them.
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 ¶
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) PostJSONWithHeaders(url string, headers map[string]string, body interface{}, timeout time.Duration) (code int, resBody []byte, err error) GetWithHeaders(url string, headers map[string]string, timeout time.Duration) (code int, resBody []byte, err error) }
SimpleHTTPClient defines some http functions used frequently.
var DefaultHTTPClient SimpleHTTPClient = &defaultHTTPClient{}
DefaultHTTPClient is the default implementation of SimpleHTTPClient.
type SyncMap ¶
SyncMap is a thread-safe map.
func (*SyncMap) Add ¶
Add add a key-value pair into the *sync.Map. The ErrEmptyValue error will be returned if the key is empty.
func (*SyncMap) Get ¶
Get returns result as interface{} according to the key. The ErrEmptyValue error will be returned if the key is empty. And the ErrDataNotFound error will be returned if the key cannot be found.
func (*SyncMap) GetAsAtomicInt ¶
GetAsAtomicInt returns result as *AtomicInt. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) GetAsBitset ¶
GetAsBitset returns result as *bitset.BitSet. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) GetAsBool ¶
GetAsBool returns result as bool. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) GetAsInt ¶
GetAsInt returns result as int. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) GetAsMap ¶
GetAsMap returns result as SyncMap. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) GetAsString ¶
GetAsString returns result as string. The ErrConvertFailed error will be returned if the assertion fails.
func (*SyncMap) ListKeyAsIntSlice ¶
ListKeyAsIntSlice returns the list of keys as a int slice.
func (*SyncMap) ListKeyAsStringSlice ¶
ListKeyAsStringSlice returns the list of keys as a string slice.