common

package
v1.8.4 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2019 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

chan实现trylock乐观锁

file 文件相关的一些辅助函数

* 采用cas实现乐观锁及TryLock Compare And Swap 简称CAS,在sync/atomic包种 这类原子操作由名称以‘CompareAndSwap’为前缀的若干个函数代表。 声明如下

func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)

调用函数后,会先判断参数addr指向的被操作值与参数old的值是否相等 仅当此判断得到肯定的结果之后,才会用参数new代表的新值替换掉原先的旧值,否则操作就会被忽略。 so, 需要用for循环不断进行尝试,直到成功为止

使用锁的做法趋于悲观

我们总假设会有并发的操作要修改被操作的值,并使用锁将相关操作放入临界区中加以保护

使用CAS操作的做法趋于乐观

总是假设被操作值未曾被改变(即与旧值相等),并一旦确认这个假设的真实性就立即进行值替换。

*

  • 每天流动式日志实现
  • 操作日志记录到文件,支持info,error,debug,notice,alert等
  • 写日志文件的时候,采用乐观锁方式对文件句柄进行加锁
  • 等级参考php Monolog/logger.php
  • 日志切割机制参考lumberjack包实现
  • json encode采用jsoniter库快速json encode处理

str 字符串相关的辅助函数,实现方式参考php str字符串函数实现

str_convert 字符串,数字相互转换的一些辅助函数

* 在sync.Mutex基础上,实现乐观锁TryLock

Index

Constants

View Source
const (
	EMERGENCY = "emerg"  // 严重错误: 导致系统崩溃无法使用
	ALTER     = "alter"  // 警戒性错误: 必须被立即修改的错误
	CRIT      = "crit"   // 临界值错误: 超过临界值的错误,例如一天24小时,而输入的是25小时这样
	ERR       = "error"  // 一般错误:比如类型错误,数据库连接不上等等
	WARN      = "warn"   // 警告性错误: 需要发出警告的错误
	NOTICE    = "notice" // 通知: 程序可以运行但是还不够完美的错误
	INFO      = "info"   // 信息: 程序输出信息
	DEBUG     = "debug"  // 调试: 调试信息
)

日志级别 从上到下,由高到低

Variables

View Source
var LogLevelMap = map[string]int{
	EMERGENCY: 600,
	ALTER:     550,
	CRIT:      500,
	ERR:       400,
	WARN:      300,
	NOTICE:    250,
	INFO:      200,
	DEBUG:     100,
}
View Source
var TimeZone = "Asia/Shanghai" //默认时区设置,可以是Local本地时区

Functions

func Abs added in v1.7.0

func Abs(number float64) float64

Abs abs()

func Addslashes added in v1.7.0

func Addslashes(str string) string

Addslashes addslashes()

func AlterLog

func AlterLog(v interface{}, options map[string]interface{})

func Base64Decode added in v1.7.0

func Base64Decode(str string) (string, error)

Base64Decode base64_decode()

func Base64Encode added in v1.7.0

func Base64Encode(str string) string

Base64Encode base64_encode()

func Basename added in v1.7.0

func Basename(path string) string

Basename basename()

func Bin2hex added in v1.2.13

func Bin2hex(src []byte) string

Bin2hex converts binary data into hexadecimal representation

func Bindec added in v1.7.0

func Bindec(str string) (string, error)

Bindec bindec()

func CatchStack

func CatchStack() []byte

CatchStack 捕获指定stack信息,一般在处理panic/recover中处理 返回完整的堆栈信息和函数调用信息

func Ceil added in v1.7.0

func Ceil(value float64) float64

Ceil ceil()

func CheckPanic

func CheckPanic()

CheckPanic check panic when exit

func CheckPathExist added in v1.1.6

func CheckPathExist(path string) bool

CheckPathExist check file or path exist

func Chmod added in v1.7.0

func Chmod(filename string, mode os.FileMode) bool

Chmod chmod()

func Chown added in v1.1.3

func Chown(name string, info os.FileInfo) error

Chown 清空文件并保持文件权限不变,并非linux chown操作 Empty the file and keep the file permissions unchanged not the linux chown operation

func Chr added in v1.2.13

func Chr(ascii int) string

================str chr,ord func====================== Chr returns a one-character string containing the character specified by ascii

func Compare added in v1.7.0

func Compare(v1, v2 string) int

This function compares whether the two version numbers are equal and whether they are greater or less than the relationship. Return value: 0 means v1 is equal to v2; 1 means v1 is greater than v2; 2 means v1 is less than v2

func CopyFile

func CopyFile(distName, srcName string) (w int64, err error)

CopyFile 复制文件到另一个文件

func Crc32 added in v1.2.13

func Crc32(str string) uint32

Crc32 calculates the crc32 polynomial of a string

func CritLog

func CritLog(v interface{}, options map[string]interface{})

func Date added in v1.7.0

func Date(format string, timestamp int64) string

Date date() Date("02/01/2006 15:04:05 PM", 1524799394)

func DeAES

func DeAES(in, key, iv []byte) ([]byte, error)

func DebugLog

func DebugLog(v interface{}, options map[string]interface{})

func Decbin added in v1.7.0

func Decbin(number int64) string

Decbin decbin()

func EmergLog

func EmergLog(v interface{}, options map[string]interface{})

func Empty added in v1.7.0

func Empty(val interface{}) bool

Empty empty()

func EnAES

func EnAES(in, key, iv []byte) ([]byte, error)

=================str aes/des func========================== key = "abcdefghijklmnopqrstuvwxyz123456" iv = "0123456789ABCDEF"

func ErrorLog

func ErrorLog(v interface{}, options map[string]interface{})

func Explode added in v1.2.13

func Explode(delimiter, str string) []string

=================str explode,implode,strlen================ Explode returns an slice of strings, each of which is a substring of str formed by splitting it on boundaries formed by the string delimiter.

func Fclose added in v1.7.0

func Fclose(handle *os.File) error

Fclose fclose()

func Fgetcsv added in v1.7.0

func Fgetcsv(handle *os.File, length int, delimiter rune) ([][]string, error)

Fgetcsv fgetcsv()

func FileChown added in v1.7.0

func FileChown(filename string, uid, gid int) bool

Chown chown()

func FileExists added in v1.7.0

func FileExists(filename string) bool

FileExists file_exists()

func FileGetContents added in v1.7.0

func FileGetContents(filename string) (string, error)

FileGetContents file_get_contents()

func FilePutContents added in v1.7.0

func FilePutContents(filename string, data string, mode os.FileMode) error

FilePutContents file_put_contents()

func FileSize added in v1.7.0

func FileSize(filename string) (int64, error)

FileSize filesize()

func Filebase

func Filebase(file string) string

Filebase 获取文件的名称不带后缀 Get the name of the file without a suffix

func Fileline

func Fileline(file string, line int) string

Fileline 获取文件名:行数

func Filemtime added in v1.7.0

func Filemtime(filename string) (int64, error)

Filemtime filemtime()

func Float64ToStr added in v1.2.13

func Float64ToStr(f64 float64) string

Float64ToStr float64 to string 'e' (-d.dddde±dd,十进制指数)

func Floor added in v1.7.0

func Floor(value float64) float64

Floor floor()

func FormatNow

func FormatNow() string

format time.Now() use FormatTime

func FormatTime

func FormatTime(t time.Time) string

format a time.Time to string as 2006-01-02 15:04:05.999

func FormatTime19

func FormatTime19(t time.Time) string

format a time.Time to string as 2006-01-02 15:04:05 将time.time转换为日期格式

func FormatUTC

func FormatUTC() string

format time.Now().UTC() use FormatTime

func GetCurrentLocalTime

func GetCurrentLocalTime() string

当前本地时间

func GetLoc

func GetLoc(zone string) *time.Location

获取时区loc

func GetTimeByTimeZone

func GetTimeByTimeZone(zone string) string

func Getcwd added in v1.7.0

func Getcwd() (string, error)

Getcwd getcwd()

func Glob added in v1.7.0

func Glob(pattern string) ([]string, error)

Glob glob()

func Gunzip

func Gunzip(in []byte) ([]byte, error)

Gunzip decompress data user gunzip

func Gzip

func Gzip(in []byte) ([]byte, error)

Gzip compress data use gzip

func HTMLSpecialchars added in v1.2.13

func HTMLSpecialchars(str string) string

=====================html special characters================ HTMLSpecialchars converts special characters to HTML entities

func HTMLSpecialcharsDecode added in v1.2.13

func HTMLSpecialcharsDecode(str string) string

HTMLSpecialcharsDecode converts special HTML entities back to characters

func HTTPBuildQuery added in v1.7.0

func HTTPBuildQuery(queryData url.Values) string

HTTPBuildQuery http_build_query()

func Hash

func Hash(mem []byte) uint64

Hash : []byte to uint64

func Hex2bin added in v1.2.13

func Hex2bin(str string) []byte

Hex2bin decodes a hexadecimally encoded binary string

func IP2long added in v1.7.0

func IP2long(ipAddress string) uint32

========================ip convert=========== IP2long ip2long() IPv4

func Implode added in v1.2.13

func Implode(glue string, pieces []string) string

Implode returns a string containing a string representation of all the slice elements in the same order, with the glue string between each element.

func InfoLog

func InfoLog(v interface{}, options map[string]interface{})

func Int64ToStr

func Int64ToStr(i64 int64) string

Int64ToStr int64-->string

func IntToStr

func IntToStr(n int) string

================str,int,int64,float64 conv func======================= IntToStr int-->string

func IsDir added in v1.7.0

func IsDir(filename string) (bool, error)

IsDir is_dir()

func IsFile added in v1.7.0

func IsFile(filename string) bool

IsFile is_file()

func IsNumeric added in v1.7.0

func IsNumeric(val interface{}) bool

IsNumeric is_numeric() Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. In PHP hexadecimal (e.g. 0xf4c3b00c) is not supported, but IsNumeric is supported.

func IsReadable added in v1.7.0

func IsReadable(filename string) bool

IsReadable is_readable()

func IsWriteable added in v1.7.0

func IsWriteable(filename string) bool

IsWriteable is_writeable()

func Krand

func Krand(size int, kind int) string

================str krand func=========== Krand 根据kind生成不同风格的指定区间随机字符串 纯数字kind=0,小写字母kind=1 大写字母kind=2,数字+大小写字母kind=3

func LcFirst added in v1.7.0

func LcFirst(str string) string

LcFirst lcfirst()

func LoadGobData

func LoadGobData(data interface{}, fileName string)

LoadGobData 将gob写入的内容,载入到data中

func LogSize added in v1.1.3

func LogSize(n int64)

func LogSplit added in v1.1.3

func LogSplit(b bool)

日志分割设置

func Long2ip added in v1.7.0

func Long2ip(properAddress uint32) string

Long2ip long2ip() IPv4

func Ltrim added in v1.7.0

func Ltrim(str string, characterMask ...string) string

Ltrim ltrim()

func Max added in v1.7.0

func Max(nums ...float64) float64

Max max()

func MbStrlen added in v1.7.0

func MbStrlen(str string) int

MbStrlen mb_strlen()

func Md5

func Md5(str string) string

==============str md5,md5File,sha1,crc32,bin2hex,hex2bin,hash func======= Other advanced functions, please see the thinkgo/crypto package. md5 func

func Md5File added in v1.2.13

func Md5File(filename string) (string, error)

Md5File calculates the md5 hash of a given file

func Min added in v1.7.0

func Min(nums ...float64) float64

Min min()

func Mkdir added in v1.7.0

func Mkdir(filename string, mode os.FileMode) error

Mkdir mkdir()

func NewUUID

func NewUUID() string

=================uuid,rnduuid,uniqid func==================== NewUUID 通过随机数的方式生成uuid 如果rand.Read失败,就按照当前时间戳+随机数进行md5方式生成 该方式生成的uuid有可能存在重复值 返回格式:7999b726-ca3c-42b6-bda2-259f4ac0879a

func NoticeLog

func NoticeLog(v interface{}, options map[string]interface{})

func NumberNow

func NumberNow() uint64

format time.Now() use NumberTime

func NumberTime

func NumberTime(t time.Time) uint64

format a time.Time to number as 20060102150405999

func NumberUTC

func NumberUTC() uint64

format time.Now().UTC() use NumberTime

func Ord added in v1.2.13

func Ord(character string) rune

Ord return ASCII value of character

func ParseNumber

func ParseNumber(t uint64) (time.Time, error)

func ParseNumberUTC

func ParseNumberUTC(t uint64) (time.Time, error)

func ParseTime

func ParseTime(s string) (time.Time, error)

parse a string to time.Time

func ParseTimeUTC

func ParseTimeUTC(s string) (time.Time, error)

parse a string as "2006-01-02 15:04:05.999" to time.Time

func Pathinfo added in v1.7.0

func Pathinfo(path string, options int) map[string]string

Pathinfo pathinfo() -1: all; 1: dirname; 2: basename; 4: extension; 8: filename Usage: Pathinfo("/home/go/path/src/php2go/php2go.go", 1|2|4|8)

func Rand added in v1.7.0

func Rand(min, max int) int

Rand rand() Range: [0, 2147483647]

func RandInt64

func RandInt64(min, max int64) int64

生成m-n之间的随机数

func Rawurldecode added in v1.7.0

func Rawurldecode(str string) (string, error)

Rawurldecode rawurldecode()

func Rawurlencode added in v1.7.0

func Rawurlencode(str string) string

Rawurlencode rawurlencode()

func Realpath added in v1.7.0

func Realpath(path string) (string, error)

Realpath realpath()

func RecoverLog added in v1.1.9

func RecoverLog()

RecoverLog 异常捕获处理,对于异常或者panic进行捕获处理 记录到日志中,方便定位问题

func Rename added in v1.7.0

func Rename(oldname, newname string) error

Rename rename()

func RndUuid

func RndUuid() string

RndUuid 基于时间ns和随机数实现唯一的uuid 在单台机器上是不会出现重复的uuid 如果要在分布式的架构上生成不重复的uuid 只需要在rndStr的前面加一些自定义的字符串 返回格式:eba1e8cd-0460-4910-49c6-44bdf3cf024d

func RndUuidMd5

func RndUuidMd5() string

RndUuidMd5 uuid

func Round

func Round(f float64, n int) float64

对浮点数进行四舍五入操作比如 12.125保留2位小数==>12.13

func Rtrim added in v1.7.0

func Rtrim(str string, characterMask ...string) string

Rtrim rtrim()

func RunShell

func RunShell(exeStr string) (string, error)

RunShell 运行shell脚本

func SetLogDir

func SetLogDir(dir string)

日志存放目录

func SetLogTimeZone

func SetLogTimeZone(timezone string)

设置日志记录时区

func SetTimeZone

func SetTimeZone(zone string)

func Sha1

func Sha1(str string) string

sha1 string

func Sha1File added in v1.2.13

func Sha1File(path string) (string, error)

Sha1File calculates the sha1 hash of a file

func Sleep added in v1.7.0

func Sleep(t int64)

Sleep sleep()

func Stat added in v1.7.0

func Stat(filename string) (os.FileInfo, error)

Stat stat()

func StoreGobData

func StoreGobData(data interface{}, fileName string) error

func StrJoin

func StrJoin(sep string, str ...string) string

===================str join func======================== StrJoin 多个字符串按照指定的分隔符进行拼接

func StrJoinByBuf

func StrJoinByBuf(str ...string) string

StrJoinByBuf 通过buf缓冲区的方式连接字符串

func StrRepeat added in v1.7.0

func StrRepeat(input string, multiplier int) string

StrRepeat str_repeat()

func StrReplace added in v1.7.0

func StrReplace(search, replace, subject string, count int) string

StrReplace str_replace()

func StrShuffle added in v1.7.0

func StrShuffle(str string) string

StrShuffle str_shuffle()

func StrToFloat64 added in v1.2.13

func StrToFloat64(str string) float64

StrToFloat64 string--->float64

func StrToInt

func StrToInt(s string) int

StrToInt string-->int

func StrToInt64

func StrToInt64(s string) int64

StrToInt64 string--> int64

func StringMapKeys

func StringMapKeys(m interface{}) (res []string)

func Stripos added in v1.2.13

func Stripos(haystack, needle string) int

Stripos find position of the first occurrence of a case-insensitive substring in a string

func Stripslashes added in v1.7.0

func Stripslashes(str string) string

Stripslashes stripslashes()

func Strlen added in v1.2.13

func Strlen(str string) int

Strlen get string length A multi-byte character is counted as 1

func Strpos added in v1.2.13

func Strpos(haystack, needle string) int

=================str strpos,Strrpos,stripos,Strripos func==================== Strpos find position of first occurrence of string in a string It's multi-byte safe. return -1 if can not find the substring

func Strripos added in v1.2.13

func Strripos(haystack, needle string) int

Strripos find the position of the last occurrence of a case-insensitive substring in a string

func Strrpos added in v1.2.13

func Strrpos(haystack, needle string) int

Strrpos find the position of the last occurrence of a substring in a string

func Strstr added in v1.7.0

func Strstr(haystack string, needle string) string

Strstr strstr()

func Strtolower added in v1.7.0

func Strtolower(str string) string

Strtolower strtolower()

func Strtotime added in v1.7.0

func Strtotime(format, strtime string) (int64, error)

Strtotime strtotime() Strtotime("02/01/2006 15:04:05", "02/01/2016 15:04:05") == 1451747045 Strtotime("3 04 PM", "8 41 PM") == -62167144740

func Strtoupper added in v1.7.0

func Strtoupper(str string) string

Strtoupper strtoupper()

func Substr added in v1.7.0

func Substr(str string, start uint, length int) string

Substr substr()

func Time added in v1.7.0

func Time() int64

Time time()

func Touch added in v1.7.0

func Touch(filename string) (bool, error)

Touch touch()

func Trim added in v1.7.0

func Trim(str string, characterMask ...string) string

Trim trim()

func URLDecode added in v1.7.0

func URLDecode(str string) (string, error)

URLDecode urldecode()

func URLEncode added in v1.7.0

func URLEncode(str string) string

URLEncode urlencode()

func UcFirst added in v1.7.0

func UcFirst(str string) string

UcFirst ucfirst()

func Ucwords added in v1.7.0

func Ucwords(str string) string

Ucwords ucwords()

func Uniqid added in v1.7.0

func Uniqid(prefix string) string

Uniqid uniqid()

func Unlink(filename string) error

Unlink unlink()

func Usleep added in v1.7.0

func Usleep(t int64)

Usleep usleep()

func Uuid added in v1.1.6

func Uuid() string

func VersionCompare added in v1.7.0

func VersionCompare(v1, v2, operator string) bool

VersionCompare compare str1,str2 eg 1.2.1 >= 1.2.0

func WarnLog

func WarnLog(v interface{}, options map[string]interface{})

func Xss

func Xss(str string) string

=====================str xss,XssUnescape func============= Xss 防止xss攻击

func XssUnescape

func XssUnescape(str string) string

Types

type ChanLock

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

func NewChanLock

func NewChanLock() *ChanLock

NewChanLock 实例化一个通道空结构体锁对象

func (*ChanLock) Lock

func (l *ChanLock) Lock()

Lock 通道枷锁

func (*ChanLock) TryLock

func (l *ChanLock) TryLock() bool

TryLock 乐观锁实现

func (*ChanLock) TryLockTimeout

func (l *ChanLock) TryLockTimeout(timeout time.Duration) bool

TryLockTimeout 指定时间内的乐观锁

func (*ChanLock) Unlock

func (l *ChanLock) Unlock()

Unlock实现通道解锁

type EmptyArray added in v1.1.5

type EmptyArray []struct{}

EmptyArray 兼容其他语言的[]空数组,一般在tojson的时候转换为[]

type EmptyStruct

type EmptyStruct struct{}

EmptyStruct zero size, empty struct

type H added in v1.1.5

type H map[string]interface{}

H 对map[string]interface{}别名类型,简化书写

type Lock

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

func NewLock

func NewLock() *Lock

func (*Lock) Lock

func (this *Lock) Lock()

func (*Lock) SchedLock

func (this *Lock) SchedLock()

func (*Lock) SpinLock

func (this *Lock) SpinLock(count int) bool

不断地尝试原子地更新flag的值,直到操作成功为止

func (*Lock) TimeoutSchedLock

func (this *Lock) TimeoutSchedLock(t time.Duration) bool

func (*Lock) TimeoutSpinLock

func (this *Lock) TimeoutSpinLock(t time.Duration) bool

func (*Lock) TryLock

func (this *Lock) TryLock() bool

尝试枷锁

func (*Lock) Unlock

func (this *Lock) Unlock()

释放锁

type Mutex

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

func NewMutexLock

func NewMutexLock() *Mutex

NewMutexLock 创建lock实例

func (*Mutex) Lock

func (m *Mutex) Lock()

Lock 枷锁

func (*Mutex) TryLock

func (m *Mutex) TryLock() bool

TryLock 尝试枷锁

func (*Mutex) Unlock

func (m *Mutex) Unlock()

Unlock 解锁

type Semaphore

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

分配安全的bool chan

func NewSemaphore

func NewSemaphore(capa int) *Semaphore

func (*Semaphore) Alloc

func (this *Semaphore) Alloc()

func (*Semaphore) Free

func (this *Semaphore) Free() bool

func (*Semaphore) TryAlloc

func (this *Semaphore) TryAlloc() bool

type StringList

type StringList []string

StringList: str list

func (StringList) Count

func (this StringList) Count() int

func (StringList) Delete

func (this StringList) Delete(token string) int

func (StringList) IsEmpty

func (this StringList) IsEmpty() bool

func (StringList) Len

func (this StringList) Len() int

func (StringList) Less

func (this StringList) Less(i, j int) bool

func (StringList) Swap

func (this StringList) Swap(i, j int)

func (StringList) UniqueAdd

func (this StringList) UniqueAdd(token string) StringList

type TaskRes added in v1.1.5

type TaskRes struct {
	Err      error
	Result   chan interface{}
	CostTime float64
}

dotask返回的结果

func DoTask added in v1.1.5

func DoTask(fn func() interface{}) *TaskRes

DoTask 在独立携程中运行fn 这里返回结果设计为interface{},因为有时候返回结果可以是error

func DoTaskWithArgs added in v1.1.5

func DoTaskWithArgs(fn func(args ...interface{}) interface{}, args ...interface{}) *TaskRes

DoTaskWithArgs 在独立携程中执行有参数的fn

func DoTaskWithContext added in v1.1.5

func DoTaskWithContext(ctx context.Context, fn func() interface{}, timeout time.Duration) *TaskRes

DoTaskWithContext 通过上下文context+done+select实现goroutine超时调用

func DoTaskWithContextArgs added in v1.1.5

func DoTaskWithContextArgs(ctx context.Context, fn func(args ...interface{}) interface{}, timeout time.Duration, args ...interface{}) *TaskRes

DoTaskWithContextArgs 通过上下文context+done+select实现goroutine超时调用

func DoTaskWithTimeout added in v1.1.5

func DoTaskWithTimeout(fn func() interface{}, timeout time.Duration) *TaskRes

DoTaskWithTimeout 采用done+select+time.After实现goroutine超时调用

func DoTaskWithTimeoutArgs added in v1.1.5

func DoTaskWithTimeoutArgs(fn func(args ...interface{}) interface{}, timeout time.Duration, args ...interface{}) *TaskRes

DoTaskWithTimeoutArgs 采用done+select+time.After实现goroutine超时调用

Jump to

Keyboard shortcuts

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