lodago

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: May 8, 2020 License: MIT Imports: 18 Imported by: 0

README

Lodago

It has the same goal as the lodash library, providing rich functions for golang.

Function

  • UUID - Generate the uuid string
  • Str2MD5 - Converts the string to md5
  • Find - Find a specific element in sclice
  • Filter - Filter a slice
  • Shuffle - Shuffle a slice
  • SelectFields - Output json based on the selected field
  • DropFields - Output json based on the drop field
  • Struct2Map - Converts the struct to map
  • Map2Struct - Converts the map to struct
  • Map2JSON - Converts the map to json
  • JSON2Map - Converts the json to map
  • Concat - Concat multi slice
  • After - The function does not actually execute until it has been called n times
  • Before - The function does not execute when it is greater than n
  • Remove - Remove a element in slice by index
  • LowerFirst - Lower first char
  • UpperFirst - Upper first char
  • CamelCase - Converts string to camelCase, group_id -> groupId
  • SnakeCase - Converts string to SnakeCase, GroupId -> group_id
  • IsEqual - Same as reflect.DeepEqual() function
  • String2Bytes - Zero copy convert string to []byte
  • Bytes2String - Zero copy convert []byte to string
  • RandString - Random characters
  • RandStrWithNum - Random generate string with number[0-9]
  • RandStrWithLower - Random generate string with lower case[a-z]
  • RandStrWithUpper - Random generate string with upper case[A-Z]
  • If - Ternary expression
  • Hash - Get hash value of string
  • Multimap - A multi key-value map.
  • DropMapFields - Output map based on the drop field
  • Queue - A thread-safe queue.
  • Crontab - A cron library for go.

Demo

  • UUID
func main() {
	fmt.Println(lodago.UUID())
}

result

9de5f29c-b744-4b3e-b0c6-b5c1e3705510
  • Str2MD5
func main() {
    str := []byte("test12345")
    fmt.Println(lodago.Str2MD5(str))
}

result

c06db68e819be6ec3d26c6038d8e8d1f
  • Find
type User struct {
	ID            int
	Name          string
}

func main() {
	users := []User {
		User{1, "张三"},
		User{2, "李四"},
		User{3, "赵四"},
	}

	findID := 2

	user, isFound := lodago.Find(users, func(ele interface{}, index int) bool {
		return ele.(User).ID == findID
	})
	if isFound {
		fmt.Println(user.(User))
	}
}

result

{2 李四}
  • Filter
type User struct {
	ID   int
	Name string
}

func main() {
	users := []User{
		User{1, "张三"},
		User{2, "李四"},
		User{3, "赵四"},
	}

	id := 2

	filterUsers, isFound := lodago.Filter(users, func(ele interface{}, index int) bool {
		return ele.(User).ID != id
	})
	if isFound {
		fmt.Println(filterUsers.([]User))
	}
}

result

[{1 张三} {3 赵四}]
  • Shuffle
func main() {
	array := []string{"a", "b", "c", "d", "e", "f"}
	fmt.Println("打乱前:", array)
	lodago.Shuffle(array)
	fmt.Println("打乱后:", array)
}

result

打乱前: [a b c d e f]
打乱后: [b c f a d e]
  • SelectFields
type SearchResult struct {
	Date     string `json:"date"`
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

func main() {
	result := SearchResult{
		Date:     "2020-03-30",
		ID:       1,
		Name:     "张三",
		Password: "123456",
	}
	fields := []string{"name", "id"}
	out, _ := lodago.SelectFields(&result, fields...)
	fmt.Println(string(out))
}

result

{"id":1,"name":"张三"}
  • DropFields
type SearchResult struct {
	Date     string `json:"date"`
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

func main() {
	result := SearchResult{
		Date:     "2020-03-30",
		ID:       1,
		Name:     "张三",
		Password: "123456",
	}
    fields := []string{"password"}
	out, _ := lodago.DropFields(&result, fields...)
	fmt.Println(string(out))
}

result

{"date":"2020-03-30","id":1,"name":"张三"}
  • Struct2Map
type SearchResult struct {
	Date     string `json:"date"`
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

func main() {
	result := SearchResult{
		Date:     "2020-03-30",
		ID:       1,
		Name:     "张三",
		Password: "123456",
	}
	mapValues := lodago.Struct2Map(result)
	fmt.Println(mapValues)
}

result

map[Date:2020-03-30 ID:1 Name:张三 Password:123456]
  • Map2Struct
type SearchResult struct {
	Date     string `json:"date"`
	ID       int    `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

func main() {
	result := SearchResult{
		Date:     "2020-03-30",
		ID:       1,
		Name:     "张三",
		Password: "123456",
	}
	mapValues := lodago.Struct2Map(result)

	var obj SearchResult
	lodago.Map2Struct(mapValues, &obj)
	fmt.Println(obj)
}

result

{2020-03-30 1 张三 123456}
  • Map2JSON
func main() {
	mapValues := map[string]interface{}{
		"id":   1,
		"name": "peter",
	}
	jsonStr, err := lodago.Map2JSON(mapValues)
	if err == nil {
		fmt.Println(jsonStr)
	}
}

result

{"id":1,"name":"peter"}
  • JSON2Map
func main() {
	mapValues := map[string]interface{}{
		"id":   1,
		"name": "peter",
	}
	jsonStr, err := lodago.Map2JSON(mapValues)
	if err == nil {
		mapValues, err := lodago.JSON2Map([]byte(jsonStr))
		if err == nil {
			fmt.Println(mapValues)
		}
	}
}

result

map[id:1 name:peter]
  • Concat
a1 := []int{1, 2, 3}
a2 := []int{4, 5}
a3 := []int{6}
result := lodago.Concat(a1, a2, a3)
fmt.Println(result)         // interface{} type
fmt.Println(result.([]int)) // original type

result

[1 2 3 4 5 6]
[1 2 3 4 5 6]

or

type User struct {
	ID   int
	Name string
}
func main() {
	a1 := []User{User{1, "u1"}, User{2, "u2"}, User{3, "u3"}}
	a2 := []User{User{4, "u4"}, User{5, "u5"}}
	a3 := []User{User{6, "u6"}}
	result := lodago.Concat(a1, a2, a3)
	fmt.Println(result)          // interface{} type
	fmt.Println(result.([]User)) // original type
}

result

[{1 u1} {2 u2} {3 u3} {4 u4} {5 u5} {6 u6}]
[{1 u1} {2 u2} {3 u3} {4 u4} {5 u5} {6 u6}]
  • Fill
func main() {
	var slice1 []int = make([]int, 10)
	var slice2 []int = make([]int, 10)
	var slice3 []int = make([]int, 10)
	fmt.Println("slice1 origin: ", slice1)
	lodago.Fill(slice1, 6, 0, 5)
	fmt.Println("slice1 fill:   ", slice1)

	fmt.Println("slice2 origin: ", slice2)
	lodago.Fill(slice2, 7)
	fmt.Println("slice2 fill:   ", slice2)

	fmt.Println("slice3 origin: ", slice3)
	lodago.Fill(slice3, 8, 3)
	fmt.Println("slice3 fill:   ", slice3)
}

result

slice1 origin:  [0 0 0 0 0 0 0 0 0 0]
slice1 fill:    [6 6 6 6 6 0 0 0 0 0]
slice2 origin:  [0 0 0 0 0 0 0 0 0 0]
slice2 fill:    [7 7 7 7 7 7 7 7 7 7]
slice3 origin:  [0 0 0 0 0 0 0 0 0 0]
slice3 fill:    [0 0 0 8 8 8 8 8 8 8]
  • After
func main() {
	cf := lodago.After(3, func(idx int) {
		fmt.Println("idx is ", idx)
	}).(func(int))

	cf(1)
	cf(2)
	cf(3)
	cf(4)
}

result

idx is  3
idx is  4

or

func main() {
	cf := lodago.After(3, func(idx int) (string, error) {
		fmt.Println("idx is ", idx)
		return "ok", errors.New("error")
	}).(func(int) (string, error))

	fmt.Println(cf(1))
	fmt.Println(cf(2))
	fmt.Println(cf(3))
	fmt.Println(cf(4))
}

result

 <nil>
 <nil>
idx is  3
ok error
idx is  4
ok error
  • Before
func main() {
	cf := lodago.Before(3, func(idx int) {
		fmt.Println("idx is ", idx)
	}).(func(int))

	cf(1)
	cf(2)
	cf(3)
	cf(4)
}

result

idx is  1
idx is  2

or

func main() {
	cf := lodago.Before(3, func(idx int) (string, error) {
		fmt.Println("idx is ", idx)
		return "ok", errors.New("error")
	}).(func(int) (string, error))

	fmt.Println(cf(1))
	fmt.Println(cf(2))
	fmt.Println(cf(3))
	fmt.Println(cf(4))
}

result

idx is  1
ok error
idx is  2
ok error
 <nil>
 <nil>
  • Remove
// User 测试
type User struct {
	ID   int
	Name string
}

func main() {
	a := []string{"A", "B", "C", "D", "E"}
	lodago.Remove(&a, 1)
	fmt.Println(a)
	b := []int{1, 2, 3, 4, 5}
	lodago.Remove(&b, 4)
	fmt.Println(b)
	c := []User{
		User{1, "张三"},
		User{2, "李四"},
		User{3, "小芳"},
		User{4, "二狗子"},
	}
	lodago.Remove(&c, 2)
	fmt.Println(c)
}

result

[A C D E]
[1 2 3 4]
[{1 张三} {2 李四} {4 二狗子}]
  • RandString
fmt.Println("64: ", lodago.RandString()) // default 64
fmt.Println("96: ", lodago.RandString(96)) // generate 96 char

result

64:  GgvN9gz1IgESBgYQWtyrGkW4VgYQ9mdn139KnVs7YM04iKQb7mh9XuJ9Cyx6u8bU
96:  G8gxJxg0sJggvwWqll7wV55BjcoAWIxJp4OFQ8kzE9vFO3G36Xu67cr3xCXmyjgmbikYp6DMt6rvQlgVWweA3Yh2S8jmIrVx
  • RandStrWithNum
func main() {
	fmt.Println(lodago.RandStrWithNum(64))
	fmt.Println(lodago.RandStrWithLower(64))
	fmt.Println(lodago.RandStrWithUpper(64))
}

result

9968498101165183260988712812608745823453372706940069839172999688
mzkqmsuaatexepfmexthnrdcgnigomrnvvybwbqddifpcpziumrefjshngrtyqjk
WSPQEMFMSCOSFRGXEEEEIJLSMUXINUDZHVULHXTMDXZPJDSVKEGTMWEWRUIPIBYN
  • multimap
func main() {
	m := lodago.NewMultimap()
	m.Insert("key1", 1)
	m.Insert("key1", 1)
	m.Insert("key1", 3)
	m.Insert("key1", 4)
	m.Insert("key1", 5)
	fmt.Println(m.Size())
	fmt.Println(m.At("key1"))
	m.Remove("key1", 3)
	fmt.Println(m.Size())
	fmt.Println(m.At("key1"))
}

result

5
[1 1 3 4 5] true
4
[1 1 4 5] true
  • Queue
var q = lodago.NewQueue(1024*1024, time.Duration(10)*time.Microsecond)

func putExample(data int) {
	// if queue is full, Put will sleep and runtime.Gosched()
	ok, _ := q.Put(data)
	for !ok {
		ok, _ = q.Put(data)
	}
}

func getExample() int {
	// if queue is empty, Get will sleep and runtime.Gosched()
	val, ok, _ := q.Get()
	for !ok {
		val, ok, _ = q.Get()
	}
	return val.(int)
}

func main() {
	putExample(1)
	putExample(2)
	putExample(3)
	putExample(4)
	putExample(5)
	putExample(6)
	fmt.Println(getExample())
	fmt.Println(getExample())
	fmt.Println(getExample())
	fmt.Println(getExample())
	fmt.Println(getExample())
	fmt.Println(getExample())
}

result

1
2
3
4
5
6
  • Crontab
c := lodago.NewCrontab()
go c.Start()
defer c.Stop()

t := lodago.CronTime{
	lodago.Once,
	"2020",
	"5",
	"8",
	"14",
	"19",
	"",
	"",
}
job1 := func() {
	fmt.Println("一次性任务")
}
c.AddJob(&t, job1)

for {
	time.Sleep(time.Duration(1 * time.Second))
	fmt.Println(c.GetEntries())
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func After added in v0.1.5

func After(n int, fun interface{}) interface{}

After 在执行几次后才真正执行

func Before added in v0.2.1

func Before(n int, fun interface{}) interface{}

Before 在执行几次之后不再执行

func Bytes2String added in v0.1.6

func Bytes2String(b []byte) string

Bytes2String byte切片转换字符串 零拷贝

func CamelCase added in v0.1.6

func CamelCase(s string, sep ...string) string

CamelCase "group_id" -> "groupId"

func Concat added in v0.1.4

func Concat(arr1 interface{}, arr2 ...interface{}) interface{}

Concat 拼接切片

func DropFields

func DropFields(v interface{}, fields ...string) ([]byte, error)

DropFields 选择性的抛弃struct的一些字段

func DropMapFields added in v0.2.4

func DropMapFields(m map[string]interface{}, keys ...string) (map[string]interface{}, error)

DropMapFields 针对map选择性字段

func Fill added in v0.1.4

func Fill(arr interface{}, value interface{}, options ...int)

Fill 填充切片

func Filter

func Filter(arr interface{}, callback func(ele interface{}, index int) bool) (interface{}, bool)

Filter 切片元素过滤

func Find

func Find(arr interface{}, callback func(ele interface{}, index int) bool) (interface{}, bool)

Find 数组查找函数

func Hash added in v0.2.3

func Hash(str string) uint64

Hash 哈希值

func If added in v0.2.2

func If(condition bool, trueValue, falseValue interface{}) interface{}

If 三元表达式 If(a > b, c, d)

func IsEqual added in v0.1.5

func IsEqual(obj1 interface{}, obj2 interface{}) bool

IsEqual 判断两个对象是否相同

func IsFunc added in v0.2.1

func IsFunc(fun interface{}) bool

IsFunc 是否为函数

func IsNum added in v0.2.5

func IsNum(s string) bool

IsNum 判断字符串是不是整数

func JSON2Map

func JSON2Map(jsonStr []byte) (map[string]interface{}, error)

JSON2Map json字符串转换成map容器

func LowerFirst added in v0.1.6

func LowerFirst(s string) string

LowerFirst ABC -> aBC

func Map2JSON

func Map2JSON(mapValue map[string]interface{}) (string, error)

Map2JSON map容器转换成json字符串

func Map2Struct

func Map2Struct(mapValue map[string]interface{}, obj interface{}) error

Map2Struct 将map对象转换成结构体

func RandStrWithLower added in v0.2.0

func RandStrWithLower(n ...int) string

RandStrWithLower 随机生成小写字母字符串

func RandStrWithNum added in v0.2.0

func RandStrWithNum(n ...int) string

RandStrWithNum 随机生成数字字符串

func RandStrWithUpper added in v0.2.0

func RandStrWithUpper(n ...int) string

RandStrWithUpper 随机生成大写字母字符串

func RandString added in v0.1.9

func RandString(n ...int) string

RandString 随机字符串(数字 + 大小写字母)

func Remove added in v0.1.5

func Remove(arr interface{}, index int, order ...bool)

Remove 移除索引位置的元素

func SelectFields

func SelectFields(v interface{}, fields ...string) ([]byte, error)

SelectFields 针对性的选择struct字段输出

func Shuffle

func Shuffle(arr interface{})

Shuffle 打乱数组

func SnakeCase added in v0.1.6

func SnakeCase(s string, sep ...string) string

SnakeCase "GroupId" -> "group_id"

func Str2MD5

func Str2MD5(str []byte) string

Str2MD5 字符串转换成md5加密

func String2Bytes added in v0.1.6

func String2Bytes(s string) []byte

String2Bytes 字符串转换byte切片 零拷贝

func Struct2Map

func Struct2Map(obj interface{}) map[string]interface{}

Struct2Map 利用反射将结构体转化为map

func UUID

func UUID() string

UUID 生成唯一的uuid

func UpperFirst added in v0.1.6

func UpperFirst(s string) string

UpperFirst abc -> Abc

Types

type CronTime added in v0.2.5

type CronTime struct {
	Type   ScheduleType `json:"type"`
	Year   string       `json:"year"`
	Month  string       `json:"month"`
	Day    string       `json:"day"`
	Hour   string       `json:"hour"`
	Minute string       `json:"minute"`
	Week   string       `json:"week"`
	Key    string       `json:"key"`
}

CronTime 时间结构

func (*CronTime) ToSpec added in v0.2.5

func (c *CronTime) ToSpec() (string, error)

ToSpec 转换成spec函数 【周期性】 【每年】 输入[月][日][时][分] -- 30 22 1 1 * 每年的1月1日22点30分执行 【已验证】 【每月】 输入[日][时][分] -- 30 22 1 * * 每月1日22点30分执行 【已验证】 【每天】 输入[时][分] -- 30 22 * * * 每天22点30分执行,【已验证】 【每周】 输入[星期][时][分] -- 30 22 * * 1 每周一22点30分执行 【已验证】 【每小时】输入[分] -- 15 * * * * 每小时的15分执行 【已验证】 【每隔几月】 输入[月][日][时][分] -- 30 22 3 */3 * 【每隔几天】 输入[日][时][分] -- 30 22 */3 * * 每隔3天的22点30分执行 【每隔小时】 输入[时][分] -- @every 1h30m 每隔1小时30分执行 【一次性】 输入[年][月][日][时][分] 由于cron不支持一次性任务,所以只能通过周期性时间删除自身解决。

type Crontab added in v0.2.5

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

Crontab 定时任务调度器

func NewCrontab added in v0.2.5

func NewCrontab() *Crontab

NewCrontab 创建定时器

func (*Crontab) AddJob added in v0.2.5

func (c *Crontab) AddJob(cronTime *CronTime, job Job) (cron.EntryID, error)

AddJob 添加任务,返回值是job id,可以用于删除任务

func (*Crontab) GetEntries added in v0.2.5

func (c *Crontab) GetEntries() []cron.Entry

GetEntries 获得所有实体

func (*Crontab) RemoveJob added in v0.2.5

func (c *Crontab) RemoveJob(id cron.EntryID)

RemoveJob 删除一个任务

func (*Crontab) Start added in v0.2.5

func (c *Crontab) Start()

Start 启动

func (*Crontab) Stop added in v0.2.5

func (c *Crontab) Stop()

Stop 停止

type Job added in v0.2.5

type Job func()

Job 任务

type Multimap added in v0.2.3

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

Multimap 允许key值重复

func NewMultimap added in v0.2.3

func NewMultimap() *Multimap

NewMultimap 构建multimap

func (*Multimap) At added in v0.2.3

func (multimap *Multimap) At(key interface{}) ([]interface{}, bool)

At 取出key对应的values

func (*Multimap) Count added in v0.2.3

func (multimap *Multimap) Count(key interface{}) int

Count 获取key对应的value数量

func (*Multimap) Insert added in v0.2.3

func (multimap *Multimap) Insert(key interface{}, value interface{})

Insert 插入一条记录

func (*Multimap) InsertValues added in v0.2.3

func (multimap *Multimap) InsertValues(key interface{}, values []interface{})

InsertValues 插入多条记录

func (*Multimap) IsEmpty added in v0.2.3

func (multimap *Multimap) IsEmpty() bool

IsEmpty 判断容器内是否为空

func (*Multimap) Remove added in v0.2.3

func (multimap *Multimap) Remove(key interface{}, value interface{})

Remove 移除一条记录

func (*Multimap) RemoveAll added in v0.2.3

func (multimap *Multimap) RemoveAll(key interface{})

RemoveAll 删除关于key的所有键值对

func (*Multimap) Size added in v0.2.3

func (multimap *Multimap) Size() int

Size 获取map当前键值对的数量

type Queue added in v0.2.4

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

Queue 无锁队列

func NewQueue added in v0.2.4

func NewQueue(capacity uint64, sleepTime time.Duration) *Queue

NewQueue 创建一个队列

func (*Queue) Get added in v0.2.4

func (q *Queue) Get() (interface{}, bool, uint64)

Get 从队列中获取记录,返回取出的值,是否成功,剩余数量。

func (*Queue) GetCapacity added in v0.2.4

func (q *Queue) GetCapacity() uint64

GetCapacity 获取容量

func (*Queue) GetQuantity added in v0.2.4

func (q *Queue) GetQuantity() uint64

GetQuantity 获取当前队列剩余多少条记录

func (*Queue) Gets added in v0.2.4

func (q *Queue) Gets(values []interface{}) (int, uint64)

Gets 获取多条记录,返回获取的记录数量,剩余数量。

func (*Queue) Put added in v0.2.4

func (q *Queue) Put(value interface{}) (bool, uint64)

Put 向队列插入数据,返回是否成功,剩余数量。

func (*Queue) Puts added in v0.2.4

func (q *Queue) Puts(values []interface{}) (int, uint64)

Puts 向队列插入多条数据,返回添加的记录数量,剩余数量。

func (*Queue) ToString added in v0.2.4

func (q *Queue) ToString() string

ToString 序列化成字符串

type ScheduleType added in v0.2.5

type ScheduleType int32

ScheduleType 时间表类型

const (
	Yearly        ScheduleType = 1 // 每年
	Monthly       ScheduleType = 2 // 每月
	Weekly        ScheduleType = 3 // 每周
	Daily         ScheduleType = 4 // 每天
	Hourly        ScheduleType = 5 // 每小时
	IntervalMonth ScheduleType = 6 // 每隔几个月
	IntervalDay   ScheduleType = 7 // 每隔几天
	Every         ScheduleType = 8 // 间隔时间,只支持[时][分]
	Once          ScheduleType = 9 // 一次性
)

定时任务的时间表类型

Jump to

Keyboard shortcuts

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