common

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2023 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// AppPath app的绝对路径,末尾带有/
	AppPath   = ""
	File_R    = os.O_RDONLY                                        // 只读
	File_W    = os.O_WRONLY                                        // 只写
	File_RW   = os.O_RDWR                                          // 可读可写
	File_WC   = os.O_WRONLY | os.O_CREATE                          // 可写 没有就创建
	File_RWC  = os.O_RDWR | os.O_CREATE                            // 可读可写 没有就创建
	File_RWCA = os.O_RDWR | os.O_CREATE | os.O_APPEND              // 可读可写 没有就创建 附加到尾部
	File_RWCT = os.O_RDWR | os.O_CREATE | os.O_APPEND | os.O_TRUNC // 可读可写 没有就创建 清空文件
)

Functions

func BoolToStr

func BoolToStr(b bool) string

func ByteToStr

func ByteToStr(b []byte) string

func ChangeStringWithIndex

func ChangeStringWithIndex(str *string, index int, s byte) string

ChangeStringWithIndex 修改string的index对应的字符 只适用英文

func ChangeStringWithIndexCN

func ChangeStringWithIndexCN(str *string, index int, s rune) string

ChangeStringWithIndexCN 修改string的index对应的字符 可以处理中文 str := "你好" s := common.ChangeStringWithIndex(&str, 0, '他') fmt.Println(s) // 他好

func ClearMap

func ClearMap[K comparable, V any](a *map[K]V)

ClearMap 清空map

a := make(map[string]string)
a["a"] = "A"
ClearMap(&a)
fmt.Println(a) // map[]

func CopyFile added in v1.0.2

func CopyFile(srcPath, destPath string, perm os.FileMode) error

CopyFile 复制文件,如果文件不存在会创建,适合小文件

err := CopyFile(common.AppPath+"a.txt", common.AppPath+"b.txt", 0755)

func CopyFileForLargeFile added in v1.0.2

func CopyFileForLargeFile(srcPath, destPath string, perm os.FileMode) error

CopyFileForLargeFile 复制大文件

err := CopyFileForLargeFile(common.AppPath+"a.txt", common.AppPath+"c.txt",0755)

func ErrorExit

func ErrorExit(err *error)

ErrorExit 如果有异常就退出程序

func test() (err error) {
	return errors.New("自定义错误")
}

err := test()
common.ErrorExit(&err)

func ErrorMethod

func ErrorMethod()

ErrorMethod 如果有异常就退出函数

func test() {
	defer common.ErrorMethod()
	i := 0
	fmt.Println("test()结束,a:", 3/i)
}

test()

func FileExist added in v1.0.2

func FileExist(filePath string) (bool, error)

FileExist 判断文件是否存在

	exist, err := FileExist(common.AppPath + "aa.txt")
	if err != nil {
		fmt.Println("发生错误")
	} else {
	    fmt.Println(exist)
 }

func Float32ToStr

func Float32ToStr(f float32, decimalLength ...int) string

Float32ToStr decimalLength:表示小数部分长度

func Float64ToStr

func Float64ToStr(f float64, decimalLength ...int) string

func ForCN

func ForCN(str string, f func(string))

ForCN utf8中汉字占3个字节

common.ForCN("abc你好", func(str string) {
	fmt.Println(str)
})

func GetFileContent added in v1.0.2

func GetFileContent(filePath string) ([]byte, error)

GetFileContent 获取文件内容

content, err := GetFileContent(common.AppPath + "a.txt")

func GetFileReader added in v1.0.2

func GetFileReader(filePath string, size int, fun func(reader *bufio.Reader) error) error

获取reader

func GetFileWriter added in v1.0.2

func GetFileWriter(filePath string, flag int, perm os.FileMode, size int, fun func(writer *bufio.Writer) error) error

获取writer

func GetTagValue added in v1.0.2

func GetTagValue(i interface{}, filedName string, tagName string) (string, error)

GetTagValue 获取属性的tag值

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func main() {
	user := User{"张三", 20}
	value, err := GetTagValue(&user, "Name", "json")
	if err != nil {
		fmt.Println("发生错误:", err)
	} else {
		fmt.Println("取到值:", value) // name
	}
}

func GoSleepSeconds added in v1.0.3

func GoSleepSeconds(n int64, fun func())

func GoUpdateWidthSeconds added in v1.0.3

func GoUpdateWidthSeconds(n int64, fun func())

GoUpdateWidthSeconds 立即执行一次,后面的每隔n秒执行一次

func IntToBase

func IntToBase[T int | int8 | int16 | int32 | int64](i T, base int) string

IntToBase 转为其他进制

func IntToStr

func IntToStr(f int, base ...int) string

func Log

func Log(a ...any)

func LogAddress

func LogAddress(str string, p any)

LogAddress 打印内存地址

func LogError

func LogError(err *error)

func LogTimeUntilDay

func LogTimeUntilDay(t ...time.Time)

LogTimeUntilDay 打印时间到日期

func LogTimeUntilSecond

func LogTimeUntilSecond(t ...time.Time)

LogTimeUntilSecond 打印时间到秒数

func LogWithBrackets

func LogWithBrackets(a ...any)

LogWithBrackets 打印的参数带方括号

func MapHasKey added in v1.0.2

func MapHasKey[T comparable](m map[T]any, key T) bool

判断map是否有key

m := make(map[string]any)
m["a"] = "a"
m["b"] = nil
fmt.Println(common.MapHasKey(m, "a")) // true
fmt.Println(common.MapHasKey(m, "b")) // true
fmt.Println(common.MapHasKey(m, "c")) // false

func NewStruct added in v1.0.2

func NewStruct[T any]() *T

创建结构体

type User struct {
	Name string
	Age  int
}

func (user User) Eat(food string) string {
	return user.Name + "吃" + food
}

func main() {
	user := common.NewStruct[User]()
	user.Name = "张三"
	fmt.Println(user.Eat("西瓜")) // 张三吃西瓜
}

func NowNanoseconds

func NowNanoseconds() int64

func NowSeconds

func NowSeconds() int64

func OpenFile

func OpenFile(fileName string, fun func(*os.File) error) error

OpenFile 打开文件

func RandFloat32

func RandFloat32() float32

func RandFloat64

func RandFloat64() float64

func RandInt

func RandInt() int

func RandInt31N

func RandInt31N(n int32) int32

func RandInt32

func RandInt32() int32

func RandInt63N

func RandInt63N(n int64) int64

func RandInt64

func RandInt64() int64

func RandIntN

func RandIntN(n int) int

func RandUInt32

func RandUInt32() uint32

func RandUint64

func RandUint64() uint64

func ReadFileBytes added in v1.0.2

func ReadFileBytes(filePath *string, fun func([]byte) error) error

user := User{}

err := common.ReadFileBytes(&filePath, func(bytes []byte) error {
	return json.Unmarshal(bytes, &user)
})

func ReadFileForString

func ReadFileForString(fileName string, fun func(str string), bufferSize ...int) error

ReadFileForString 将文件内容的每一行读取出来 适合大文件

err := common.ReadFileForString(common.AppPath+"/a.txt", func(str string) {
	common.LogWithBrackets(str)
}, 16)

func ReadWriteFile added in v1.0.2

func ReadWriteFile(fileName string, flag int, perm os.FileMode,
	fun func(reader *bufio.Reader, writer *bufio.Writer) error, bufferSize ...int) error

ReadWriteFile 可读可写

err := common.ReadWriteFile(common.AppPath+"a.txt", common.File_RWC, 0755,
	func(reader *bufio.Reader, writer *bufio.Writer) error {
		// 读取
		err := common.ReaderStringBorder(reader, func(str string) {
			common.LogWithBrackets(str)
		})
		if err != nil {
			return err
		}
		// 写入
		_, err2 := writer.WriteString("你好\r\n")
		if err2 != nil {
			return err2
		}
		return nil
	})

func ReaderStringBorder added in v1.0.2

func ReaderStringBorder(reader *bufio.Reader, fun func(str string)) error

ReaderStringBorder 从reader中读取字符串

err := ReaderStringBorder(reader, func(str string) {
	   common.LogWithBrackets(str)
})

func RunMethodByName added in v1.0.2

func RunMethodByName(i interface{}, methodName string, parameters ...any) ([]reflect.Value, error)

通过方法名称执行方法

type User struct {
	Name string
	Age  int
}

func (user User) Eat(food string) string {
	return user.Name + "吃" + food
}

func main() {
	user := User{"张三", 20}
	values, err := common.RunMethodByName(&user, "Eat", "西瓜")
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("返回结果:", values) // [张三吃西瓜]
	}
}

func SetFiledValue added in v1.0.2

func SetFiledValue[T comparable](i interface{}, filedName string, value T) error

设置值

type User struct {
	Name string
	Age  int
}

func main() {
  user := User{"张三", 20}
  err := SetFiledValue(&user, "Name", "李四")
  if err != nil {
     fmt.Println("发生错误:", err)
  }
  fmt.Println(user) // {李四 20}
}

func main() {
  user := User{"张三", 20}
  err := SetFiledValue(&user, "Name", 1)
  if err != nil {
     fmt.Println("发生错误:", err) // 发生错误: Name类型不同,期望类型:string ,实际类型:int
  }
  fmt.Println(user) // {张三 20}
}

func SleepHour

func SleepHour(i int64)

func SleepMicrosecond

func SleepMicrosecond(i int64)

func SleepMillisecond

func SleepMillisecond(i int64)

func SleepMillisecondWithRandom added in v1.0.3

func SleepMillisecondWithRandom(i int64, r int64)

func SleepMinute

func SleepMinute(i int64)

func SleepNanosecond

func SleepNanosecond(i int64)

func SleepSecond

func SleepSecond(i int64)

func SleepSecondWithRandom added in v1.0.3

func SleepSecondWithRandom(i int64, r int64)

func StrToBool

func StrToBool(str string) bool

func StrToByte

func StrToByte(str string) []byte

func StrToFloat32

func StrToFloat32(str string) float32

func StrToFloat64

func StrToFloat64(str string) float64

func StrToInt

func StrToInt(str string, base ...int) int

func StrToInt16

func StrToInt16(str string, base ...int) int16

func StrToInt32

func StrToInt32(str string, base ...int) int32

func StrToInt64

func StrToInt64(str string, base ...int) int64

func StrToInt8

func StrToInt8(str string, base ...int) int8

func TimeDay added in v1.0.2

func TimeDay(t ...time.Time) string

func TimeSecond added in v1.0.2

func TimeSecond(t ...time.Time) string

func TimeSecondPath added in v1.0.7

func TimeSecondPath() string

func Trim added in v1.0.2

func Trim(str *string) string

func TryCatch added in v1.0.2

func TryCatch(try func(), errFun func(err any)) bool

TryCatch 用于捕获异常

	type HttpError struct {
	Code int
}

func (e *HttpError) Error() string {
	return fmt.Sprintf("status code %d", e.Code)
}

type PermissionError struct {
	Code int
}

func (e *PermissionError) Error() string {
	return fmt.Sprintf("status code %d", e.Code)
}

func main() {
	common.TryCatch(func() {
		panic(HttpError{404})
	}, func(err any) {
		fmt.Println("发生异常:", err)
		switch err.(type) {
		case HttpError:
			fmt.Println("是HttpError")
		case PermissionError:
			fmt.Println("是PermissionError")
		}
	})
}

func WriteFile added in v1.0.2

func WriteFile(fileName string, flag int, perm os.FileMode, fun func(writer *bufio.Writer) error, bufferSize ...int) error

WriteFile 写入内容 fun中的异常全部往外抛,在WriteFile方法返回的err中处理异常

err := common.WriteFile(common.AppPath+"/a.txt",os.O_WRONLY|os.O_CREATE,0755,
	func(writer *bufio.Writer) error {
	for i := 0; i < 10; i++ {
		n, err := writer.WriteString("你好 " + common.IntToStr(i) + "\r\n")
		if err != nil {
			return err
		}
		fmt.Println("写入数量:", n)
	}
	return nil
})

func WriteFileBytes added in v1.0.2

func WriteFileBytes(filePath *string, data []byte, perm os.FileMode) error

err = os.WriteFile(filePath, bytes, 0755)

Types

type ChannelLock added in v1.0.2

type ChannelLock struct {
	Name string
	// contains filtered or unexported fields
}

ChannelLock 使用案例:

func set(c chan int) {
	for i := 0; i < 5; i++ {
		c <- i
		fmt.Println("set:", i)
		common.SleepSecond(1)
	}
	close(c)
}

func get(c chan int, lock *common.ChannelLock) {
	for v := range c {
		fmt.Println("	get:", v)
	}
	fmt.Println("管道已关闭")
	lock.Close()
}

func main() {
	c := make(chan int, 100)
	lock := common.NewChannelLock()
	go set(c)
	go get(c, lock)
	lock.WaitClose()
}

func NewChannelLock added in v1.0.2

func NewChannelLock(n int) *ChannelLock

NewChannelLock 创建管道锁

func NewChannelLockName added in v1.0.2

func NewChannelLockName(n int, name string) *ChannelLock

func (*ChannelLock) Close added in v1.0.2

func (lock *ChannelLock) Close()

关闭管道锁

func (*ChannelLock) WaitClose added in v1.0.2

func (lock *ChannelLock) WaitClose()

等待管道锁关闭

type MyChannel added in v1.0.2

type MyChannel[T any] struct {
	Channel chan T
	// contains filtered or unexported fields
}
func main() {
	ch := common.NewMyChannel[int](10, 2, 3)
	// ch.NewProvider(func() {
	// 	for i := 0; i < 5; i++ {
	// 		ch.channel <- i
	// 		time.Sleep(1 * time.Second)
	// 	}
	// })
	ch.NewProviderWithName("set", func(name string) {
		for i := 0; i < 5; i++ {
			ch.Channel <- i
			fmt.Println(name, i)
			time.Sleep(1 * time.Second)
		}
	})
	// ch.NewConsumer(func(v int) {
	// 	time.Sleep(200 * time.Millisecond)
	// 	fmt.Println("  ", v)
	// })
	ch.NewConsumerWithName("get", func(name string, v int) {
		time.Sleep(200 * time.Millisecond)
		fmt.Println("		", name, v)
	})
	ch.WaitProviderFinish()
	ch.WaitConsumerFinish()
}

func NewMyChannel added in v1.0.2

func NewMyChannel[T any](channelSize, providerNumber int, consumerNumber int) MyChannel[T]

func (*MyChannel[T]) NewConsumer added in v1.0.2

func (ch *MyChannel[T]) NewConsumer(fun func(value T))

func (*MyChannel[T]) NewConsumerWithName added in v1.0.2

func (ch *MyChannel[T]) NewConsumerWithName(name string, fun func(name string, value T))

func (*MyChannel[T]) NewProvider added in v1.0.2

func (ch *MyChannel[T]) NewProvider(fun func())

func (*MyChannel[T]) NewProviderWithName added in v1.0.2

func (ch *MyChannel[T]) NewProviderWithName(name string, fun func(name string))

func (*MyChannel[T]) WaitConsumerFinish added in v1.0.2

func (ch *MyChannel[T]) WaitConsumerFinish()

func (*MyChannel[T]) WaitProviderFinish added in v1.0.2

func (ch *MyChannel[T]) WaitProviderFinish()

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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