utils

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2023 License: MIT Imports: 34 Imported by: 18

README

Utils

Arrays

返回数组'array'中'val'的索引位置,返回值为:-1 表示不包含

  • Contains(array interface{}, val interface{}) (index int)
  • ContainsString(array []string, val string) (index int)
  • ContainsInt(array []int64, val int64) (index int)
  • ContainsUint(array []uint64, val uint64) (index int)
  • ContainsBool(array []bool, val bool) (index int)
  • ContainsFloat(array []float64, val float64) (index int)
  • ContainsComplex(array []complex128, val complex128) (index int)

cmd

执行系统命令返回stdout,stderr,以及可能的错误

  • ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, error) //在给定目录中执行系统命令,并以字节类型返回stdout,stderr,以及可能的错误
  • ExecCmdBytes(cmdName string, args ...string) ([]byte, []byte, error) //执行系统命令并返回stdout,以字节类型表示的stderr以及可能的错误
  • ExecCmdDir(dir, cmdName string, args ...string) (string, string, error) //在给定目录中执行系统命令并返回stdout,字符串类型的stderr以及可能的错误.
  • ExecCmd(cmdName string, args ...string) (string, string, error) //执行系统命令并返回stdout,字符串类型的stderr以及可能的错误

Convert

提供各种类型还转工具

  • StrTo(string) //转换字符串以指定类型(Uint8,Int,Int64,MustUint8,MustInt,MustInt64,Float64,String,Hash,Exist)。
  • ToStr(value interface{}, args ...int) (s string) //将任何类型转换为字符串。
  • HexStr2int(hexStr string) (int, error) //将十六进制格式字符串转换为十进制数
  • Int2HexStr(num int) (hex string) //将十进制数格式转换为十六进制字符串
  • ArrayToString(A []int, denim string) string //整形数组转换成字符串

Crypt

建立一个go,java,python通用的加解密实现包。

  • MD5(origData string) string //给指定的字符串进行MD5加密
  • Authenticate(attemptedPassword, encryptedPassword, salt string) bool //对输入的密码进行验证
  • GenerateSalt() string //通过提供加密的强随机数生成器 生成盐
  • EncryptedPassword(rawPwd string, salt string) string //生成密文
  • PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte //基于PBKDF2算法加密
  • Encrypt(origData, key []byte) ([]byte, error) //基于PKCS5Padding算法加密
  • Decrypt(cryptic, key []byte) ([]byte, error) //基于PKCS5Padding算法解密

File

提供文件操作相关工具

  • HumaneBytes(s uint64, base float64, sizes []string) string //个性化文件大小计算文件大小
  • HumaneFileSize(s uint64) string //个性化文件大小计算文件大小并生成用户友好的字符串
  • FileMTime(file string) (int64, error) //获取文件的修改时间
  • FileSize(file string) (int64, error) //获取文件大小
  • Copy(src, dest string) error //从源地址复制到目标地址
  • WriteFile(filename string, data []byte) error //将数据写入文件名指定文件,如果文件不存在,Write File将创建它及其上层路径
  • IsFile(filePath string) bool //判断给定路径是不是文件以及是否存在,如果给定的路径是文件,则返回true,或者当它是目录或不存在时返回false
  • IsExist(path string) bool //检查文件或目录是否存在,当文件或者目录不存在时返回false
  • GetGOPATH() []string // 返回GOPATH变量中的所有路径.
  • IsDir(dir string) bool // 如果给定路径是目录,则返回true;如果文件或目录不存在;则返回false.
  • StatDir(rootPath string, includeDir ...bool) ([]string, error) //通过深度优先收集给定目录的信息
  • GetAllSubDirs(rootPath string) ([]string, error) // 返回给定根路径的所有子目录,返回值不包含给定的路径.

http

提供http远程访问工具

  • HttpCall(client *http.Client, method, url string, header http.Header, body io.Reader) (io.ReadCloser, error)
  • HttpGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error)
  • HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error)
  • HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error
  • HttpGetBytes(client *http.Client, url string, header http.Header) ([]byte, error)
  • HttpGetJSON(client *http.Client, url string, v interface{}) error
  • HttpPostJSON(client *http.Client, url string, body, v interface{}) error
  • FetchFiles(client *http.Client, files []RawFile, header http.Header) error
  • FetchFilesCurl(files []RawFile, curlOptions ...string) error
  • New(ua string) *UserAgent
  • (p *UserAgent) Parse(ua string)

IP

  • ExternalIP() 获取外部IP
  • InternalIP() 获取内部IP

SyncMap

提供一个同步map操作工具

Math

提供了基于随机数生成值的工具

  • Div(n, b float64) float64 //浮点数除法
  • RandInt(start int, end int) int //随机int
  • RandInt64(start int64, end int64) int64 //随机int64
  • GenerateRandomCode() string //随机获取6位数字符串
  • GenFixedLengthChineseChars(length int) string //指定长度随机中文字符(包含复杂字符)
  • GenRandomLengthChineseChars(start, end int) string //指定范围随机中文字符
  • RandStr(len int) string //随机英文小写字母
  • RandString(n int) string //生成指定长度的随机字母和数字字符串,包括0-9、a-z、A-Z的所有字符

string

  • TokenizeToStringArray(str, delimiters string, trimTokens, ignoreEmptyTokens bool) []*string //根据分隔符进行分割处理,形成包路径数组。默认分割符为:",; \t\n"
  • Str2Bytes(s string) []byte //字符串到字节
  • Bytes2Str(b []byte) string //字节到字符串
  • StartsWith(str, prefix string, offset int) bool //判断str是以prefix开始
  • IsBlank(source string) bool //判断是否存在空格
  • HasText //判断是否有值
  • AppendStr(strs []string, str string) []string //将字符串追加到数组中,且没有重复

time

  • Date(ti int64, format string) string //将unix时间整型格式化为字符串
  • DateS(ts string, format string) string //将unix时间字符串格式化为字符串
  • DateT(t time.Time, format string) string //提供java一样格式的日期格式化方式
  • StringTime time.Time //用于提供字符日期类型json序列化互转
  • NumberTime time.Time //用于提供unix日期类型json序列化互转
  • NewDuration(str string) (dur Duration) //提供将("ns", "us" (or "µs"), "ms", "s", "m", "h")转换成time.Duration
  • NewTime(t float64) time.Time //从float64创建一个新的time.Time

License

This project is under MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

View Source
const (
	Byte  = 1
	KByte = Byte * 1024
	MByte = KByte * 1024
	GByte = MByte * 1024
	TByte = GByte * 1024
	PByte = TByte * 1024
	EByte = PByte * 1024
)

存储单元常数。

View Source
const EmptySpace = " "

EmptySpace

View Source
const EmptyString = ""

EmptyString

View Source
const TimePrecision = time.Microsecond

TimePrecision determines how precisely time is measured by this library. When serializing and deserialization tokens,time values are automatically truncated to this precision. See the time package's Truncate method for more detail

Variables

View Source
var CallUserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1541.0 Safari/537.36"
View Source
var TimeFunc = time.Now

Functions

func AesDecrypt added in v1.0.7

func AesDecrypt(data []byte, key []byte) ([]byte, error)

AesDecrypt 解密

func AesEncrypt added in v1.0.7

func AesEncrypt(data []byte, key []byte) ([]byte, error)

AesEncrypt 加密

func AppendUniqueStr added in v1.0.3

func AppendUniqueStr(strs []string, str string) []string

AppendUniqueStr 将字符串追加到数组中,且去重

func ArrayToString

func ArrayToString(A []int, denim string) string

整形数组转换成字符串

func At

func At(at time.Time) time.Time

At makes a Time value from a standard library time.Time value

func Authenticate

func Authenticate(attemptedPassword, encryptedPassword, salt string) bool

*

  • 对输入的密码进行验证 *
  • @param attemptedPassword 待验证的密码
  • @param encryptedPassword 密文
  • @param salt 盐值
  • @return 是否验证成功

func Bytes2Str

func Bytes2Str(b []byte) string

Bytes2Str

func ClearSyncMap

func ClearSyncMap(m *SyncMap)

func Concat added in v1.0.8

func Concat(str ...string) string

func Contains

func Contains(array interface{}, val interface{}) (index int)

Contains返回数组中val的索引位置,当为-1时代表不包含

func ContainsBool

func ContainsBool(array []bool, val bool) (index int)

ContainsBool返回bool类型'val'在数组中的索引位置

func ContainsComplex

func ContainsComplex(array []complex128, val complex128) (index int)

ContainsComplex返回complex128类型'val'在数组中的索引位置

func ContainsFloat

func ContainsFloat(array []float64, val float64) (index int)

ContainsFloat返回float64类型'val'在数组中的索引位置

func ContainsInt

func ContainsInt(array []int64, val int64) (index int)

ContainsInt返回int64类型'val'在数组中的索引位置

func ContainsString

func ContainsString(array []string, val string) (index int)

ContainsString返回string类型'val'在数组中的索引位置

func ContainsUint

func ContainsUint(array []uint64, val uint64) (index int)

ContainsUint返回uint64类型'val'在数组中的索引位置

func Copy

func Copy(src, dest string) error

从源地址复制到目标地址

func Date

func Date(ti int64, format string) string

将unix时间整型格式化为字符串

func DateParse

func DateParse(dateString, format string) (time.Time, error)

Parse Date use PHP time format.

func DateS

func DateS(ts string, format string) string

将unix时间字符串格式化为字符串

func DateT

func DateT(t time.Time, format string) string

Format time.Time struct to string MM - month - 01 M - month - 1, single bit DD - day - 02 D - day 2 YYYY - year - 2006 YY - year - 06 HH - 24 hours - 03 H - 24 hours - 3 hh - 12 hours - 03 h - 12 hours - 3 mm - minute - 04 m - minute - 4 ss - second - 05 s - second = 5

func Decrypt

func Decrypt(cryptic, key []byte) ([]byte, error)

func Div

func Div(n, b float64) float64

浮点数除法

func Encrypt

func Encrypt(origData, key []byte) ([]byte, error)

func EncryptedPassword

func EncryptedPassword(rawPwd string, salt string) string

*

  • 生成密文 *
  • @param rawPwd 明文密码
  • @param salt 盐值
  • @return

func ExecCmd

func ExecCmd(cmdName string, args ...string) (string, string, error)

执行系统命令并返回stdout,字符串类型的stderr以及可能的错误.

func ExecCmdBytes

func ExecCmdBytes(cmdName string, args ...string) ([]byte, []byte, error)

执行系统命令并返回stdout,以字节类型表示的stderr以及可能的错误.

func ExecCmdDir

func ExecCmdDir(dir, cmdName string, args ...string) (string, string, error)

在给定目录中执行系统命令并返回stdout,字符串类型的stderr以及可能的错误.

func ExecCmdDirBytes

func ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, error)

在给定目录中执行系统命令,并以字节类型返回stdout,stderr,以及可能的错误.

func ExternalIP

func ExternalIP() (res []string)

ExternalIP获取外部IP.

func FetchFiles

func FetchFiles(client *http.Client, files []RawFile, header http.Header) error

FetchFiles fetches files specified by the rawURL field in parallel.

func FetchFilesCurl

func FetchFilesCurl(files []RawFile, curlOptions ...string) error

FetchFiles uses command `curl` to fetch files specified by the rawURL field in parallel.

func FileMTime

func FileMTime(file string) (int64, error)

获取文件的修改时间

func FileSize

func FileSize(file string) (int64, error)

获取文件大小

func GenFixedLengthChineseChars

func GenFixedLengthChineseChars(length int) string

指定长度随机中文字符(包含复杂字符)

func GenRandomLengthChineseChars

func GenRandomLengthChineseChars(start, end int) string

指定范围随机中文字符

func GenerateRandomCode

func GenerateRandomCode() string

生成六位随机码

func GenerateSalt

func GenerateSalt() string

*

  • 通过提供加密的强随机数生成器 生成盐 *
  • @return

func GetAllSubDirs

func GetAllSubDirs(rootPath string) ([]string, error)

返回给定根路径的所有子目录,返回值不包含给定的路径.

func GetGOPATH

func GetGOPATH() []string

返回GOPATH变量中的所有路径.

func GetIP added in v1.0.6

func GetIP(r *http.Request) string

获取客户端请求IP

func HasText

func HasText(source string) bool

HasText 判断是否有值

func HexStr2int

func HexStr2int(hexStr string) (int, error)

将十六进制格式字符串转换为十进制数.

func HttpCall

func HttpCall(client *http.Client, method, url string, header http.Header, body io.Reader) (io.ReadCloser, error)

HttpCall makes HTTP method call.

func HttpGet

func HttpGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error)

HttpGet gets the specified resource. ErrNotFound is returned if the server responds with status 404.

func HttpGetBytes

func HttpGetBytes(client *http.Client, url string, header http.Header) ([]byte, error)

HttpGetBytes gets the specified resource. ErrNotFound is returned if the server responds with status 404.

func HttpGetJSON

func HttpGetJSON(client *http.Client, url string, v interface{}) error

HttpGetJSON gets the specified resource and mapping to struct. ErrNotFound is returned if the server responds with status 404.

func HttpGetToFile

func HttpGetToFile(client *http.Client, url string, header http.Header, fileName string) error

HttpGetToFile gets the specified resource and writes to file. ErrNotFound is returned if the server responds with status 404.

func HttpPost

func HttpPost(client *http.Client, url string, header http.Header, body []byte) (io.ReadCloser, error)

HttpPost posts the specified resource. ErrNotFound is returned if the server responds with status 404.

func HttpPostJSON

func HttpPostJSON(client *http.Client, url string, body, v interface{}) error

HttpPostJSON posts the specified resource with struct values, and maps results to struct. ErrNotFound is returned if the server responds with status 404.

func HumaneBytes

func HumaneBytes(s uint64, base float64, sizes []string) string

个性化文件大小计算文件大小

func HumaneFileSize

func HumaneFileSize(s uint64) string

个性化文件大小计算文件大小并生成用户友好的字符串

func Int2HexStr

func Int2HexStr(num int) (hex string)

将十进制数格式转换为十六进制字符串.

func InternalIP

func InternalIP() string

InternalIP获取内部IP.

func IsBlank

func IsBlank(source string) bool

IsBlank 判断是否存在空格

func IsDir

func IsDir(dir string) bool

如果给定路径是目录,则返回true;如果文件或目录不存在;则返回false.

func IsExist

func IsExist(path string) bool

检查文件或目录是否存在。 当文件或者目录不存在时返回false

func IsFile

func IsFile(filePath string) bool

判断给定路径是不是文件以及是否存在 如果给定的路径是文件,则返回true,或者当它是目录或不存在时返回false。

func MD5

func MD5(origData string) string

给指定的字符串进行MD5加密

func NewTime

func NewTime(t float64) time.Time

NewTime creates a new Time value from a float64

func Now

func Now() time.Time

Now returns a new Time value using the current time. You can override Now by changing the value of TimeFunc

func PBKDF2

func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte

func PKCS5Padding

func PKCS5Padding(cipher []byte, blockSize int) []byte

func PKCS5UnPadding

func PKCS5UnPadding(origData []byte) []byte

func PowInt

func PowInt(x int, y int) int

PowInt is int type of math.Pow function.

func RandInt

func RandInt(start int, end int) int

func RandInt64

func RandInt64(start int64, end int64) int64

func RandStr

func RandStr(len int) string

随机英文小写字母

func RandString

func RandString(n int) string

*

  • 生成指定长度的随机字母和数字字符串,包括0-9、a-z、A-Z的所有字符。 *
  • @param length
  • @return

func Reverse added in v1.0.3

func Reverse(s []rune) []rune

Reverse 字符翻转

func SHA1

func SHA1(data []byte) []byte

func StartsWith

func StartsWith(str, prefix string, offset int) bool

StartsWith

func StatDir

func StatDir(rootPath string, includeDir ...bool) ([]string, error)

通过深度优先收集给定目录的信息. 返回文件列表的一部分,并包括子目录(如果已启用); 当发生错误,或者给定的路径不是目录或不存在时,它将返回错误和nil数组。

返回值不包含给定的路径。 如果启用了子目录,则它们的后缀为'/'。

func Str2Bytes

func Str2Bytes(s string) []byte

Str2Bytes

func ToStr

func ToStr(value interface{}, args ...int) (s string)

将任何类型转换为字符串。

func TokenizeToStringArray

func TokenizeToStringArray(str, delimiters string, trimTokens, ignoreEmptyTokens bool) []*string

根据分隔符进行分割处理,形成包路径数组.默认分割符为:",; \t\n"

func TokenizeToStringArray1

func TokenizeToStringArray1(str, delimiters string) []*string

TokenizeToStringArray1

func WriteFile

func WriteFile(filename string, data []byte) error

将数据写入文件名指定文件。 如果文件不存在,Write File将创建它及其上层路径。

Types

type ArgAny

type ArgAny []interface{}

func (ArgAny) Get

func (a ArgAny) Get(i int, args ...interface{}) (r interface{})

type ArgInt

type ArgInt []int

func (ArgInt) Get

func (a ArgInt) Get(i int, args ...int) (r int)

type ArgString

type ArgString []string

func (ArgString) Get

func (a ArgString) Get(i int, args ...string) (r string)

type Browser

type Browser struct {
	// The name of the browser's engine.
	Engine string

	// The version of the browser's engine.
	EngineVersion string

	// The name of the browser.
	Name string

	// The version of the browser.
	Version string
}

A struct containing all the information that we might be interested from the browser.

type Duration

type Duration time.Duration

Duration be used toml unmarshal string time, like 1s, 500ms.

func NewDuration

func NewDuration(str string) (dur Duration)

func (Duration) Shrink

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText unmarshal text to duration.

type NotFoundError

type NotFoundError struct {
	Message string
}

func (NotFoundError) Error

func (e NotFoundError) Error() string

type NumberTime

type NumberTime time.Time

func (NumberTime) MarshalJSON

func (nt NumberTime) MarshalJSON() ([]byte, error)

func (*NumberTime) UnmarshalJSON

func (nt *NumberTime) UnmarshalJSON(data []byte) error

type OSInfo

type OSInfo struct {
	// Full name of the operating system. This is identical to the output of ua.OS()
	FullName string

	// Name of the operating system. This is sometimes a shorter version of the
	// operating system name, e.g. "Mac OS X" instead of "Intel Mac OS X"
	Name string

	// Operating system version, e.g. 7 for Windows 7 or 10.8 for Max OS X Mountain Lion
	Version string
}

Represents full information on the operating system extracted from the user agent.

type RawFile

type RawFile interface {
	Name() string
	RawUrl() string
	Data() []byte
	SetData([]byte)
}

A RawFile describes a file that can be downloaded.

type RemoteError

type RemoteError struct {
	Host string
	Err  error
}

func (*RemoteError) Error

func (e *RemoteError) Error() string

type StrTo

type StrTo string

转换字符串以指定类型。

func (StrTo) Exist

func (f StrTo) Exist() bool

func (StrTo) Float64

func (f StrTo) Float64() float64

func (StrTo) Hash

func (f StrTo) Hash() string

func (StrTo) Int

func (f StrTo) Int() (int, error)

func (StrTo) Int64

func (f StrTo) Int64() (int64, error)

func (StrTo) MustInt

func (f StrTo) MustInt() int

func (StrTo) MustInt64

func (f StrTo) MustInt64() int64

func (StrTo) MustUint8

func (f StrTo) MustUint8() uint8

func (StrTo) String

func (f StrTo) String() string

func (StrTo) Uint8

func (f StrTo) Uint8() (uint8, error)

type StringTime

type StringTime time.Time

func (StringTime) MarshalJSON

func (st StringTime) MarshalJSON() ([]byte, error)

实现它的json序列化方法

func (*StringTime) UnmarshalJSON

func (st *StringTime) UnmarshalJSON(data []byte) error

type SyncMap

type SyncMap struct {
	sync.Map
	sync.RWMutex
	// contains filtered or unexported fields
}

func (*SyncMap) MyDelete

func (m *SyncMap) MyDelete(key interface{})

func (*SyncMap) MyLen

func (m *SyncMap) MyLen() int64

func (*SyncMap) MyLoad

func (m *SyncMap) MyLoad(key interface{}) (value interface{}, ok bool)

func (*SyncMap) MyLoadOrStore

func (m *SyncMap) MyLoadOrStore(key, value interface{}) (actual interface{}, loaded bool)

func (*SyncMap) MyRange

func (m *SyncMap) MyRange(f func(key, value interface{}) bool)

func (*SyncMap) MyStore

func (m *SyncMap) MyStore(key, value interface{})

type UserAgent

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

包含可以从User-Agent字符串中提取的所有信息。

func New

func New(ua string) *UserAgent

解析给定的User-Agent字符串并获取结果UserAgent对象。

返回解析给定User-Agent字符串后已初始化的UserAgent对象。

func (*UserAgent) Bot

func (p *UserAgent) Bot() bool

Returns true if it's a bot, false otherwise.

func (*UserAgent) Browser

func (p *UserAgent) Browser() (string, string)

Returns two strings. The first string is the name of the browser and the second one is the version of the browser.

func (*UserAgent) Engine

func (p *UserAgent) Engine() (string, string)

Returns two strings. The first string is the name of the engine and the second one is the version of the engine.

func (*UserAgent) Localization

func (p *UserAgent) Localization() string

Returns a string containing the localization.

func (*UserAgent) Mobile

func (p *UserAgent) Mobile() bool

Returns true if it's a mobile device, false otherwise.

func (*UserAgent) Mozilla

func (p *UserAgent) Mozilla() string

Returns the mozilla version (it's how the User Agent string begins: "Mozilla/5.0 ...", unless we're dealing with Opera, of course).

func (*UserAgent) OS

func (p *UserAgent) OS() string

Returns a string containing the name of the Operating System.

func (*UserAgent) OSInfo

func (p *UserAgent) OSInfo() OSInfo

Returns combined information for the operating system.

func (*UserAgent) Parse

func (p *UserAgent) Parse(ua string)

Parse the given User-Agent string. After calling this function, the receiver will be setted up with all the information that we've extracted.

func (*UserAgent) Platform

func (p *UserAgent) Platform() string

Returns a string containing the platform..

func (*UserAgent) UA

func (p *UserAgent) UA() string

Returns the original given user agent.

Jump to

Keyboard shortcuts

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