goist

package module
v0.0.0-...-3751e5f Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2024 License: Apache-2.0 Imports: 27 Imported by: 0

README

goist

Out-of-the-box functions for go

Key features

  • Goroutine concurrency
  • Reverse proxy
  • Round-robin scheduler
  • HTTP encapsulation
  • Error management
  • Reflect utils
  • Algorithm functions
  • Write Csv and Bin files
  • Extendable

Get started

Prerequisites

Go: any one of the three latest major releases.

Getting Goist

With Go module support, simply add the following import

import "github.com/lleiiell/goist"

to your code, and then go [build|run|test] will automatically fetch the necessary dependencies.

Otherwise, run the following Go command to install the goist package:

go get -u github.com/lleiiell/goist

Documentation

For more details, please refer to https://pkg.go.dev/github.com/lleiiell/goist documentation

License

Goist is licensed under the Apache License, Version 2.0. For detail see LICENSE.

Contributing

Please see CONTRIBUTING for details on submitting patches and the contribution workflow.

We appreciate your help!

Documentation

Index

Examples

Constants

View Source
const ErrCodeApi = 3001
View Source
const ErrCodeAuth = 1003
View Source
const ErrCodeCommon = 1001
View Source
const ErrCodeDb = 2001
View Source
const ErrCodeMySQL = 2003
View Source
const ErrCodeParam = 1002
View Source
const ErrCodeRedis = 2002

Variables

This section is empty.

Functions

func AwaitAll

func AwaitAll[Input any, Response any](inputs []Input, asyncFunc func(Input) Response) []Response

func AwaitAllWRL

func AwaitAllWRL[Input any, Response any](inputs []Input, asyncFunc func(Input) Response, concurrency int) []Response

AwaitAllWRL AwaitAll with Rate Limit

func BinarySearch

func BinarySearch(nums []int, target int) bool
Example
nums := []int{22, 11, 33, 100}
target1 := 1
target2 := 11

i1 := BinarySearch(nums, target1)
i2 := BinarySearch(nums, target2)

fmt.Println(i1, i2)
Output:

false true

func BubbleSort

func BubbleSort(nums []int) []int

BubbleSort The time complexity of bubble sorting is O(n^2), which is less efficient

Example
nums := []int{22, 11, 33, 55, 44, 66}

nums2 := BubbleSort(nums)
fmt.Println(nums2)
Output:

[11 22 33 44 55 66]

func BucketSort

func BucketSort(nums []int, bucketSize int) []int
Example
nums := []int{22, 11, 33, 55, 44, 66, 7}

nums2 := BucketSort(nums, 2)
fmt.Println(nums2)
Output:

[7 11 22 33 44 55 66]

func BuildQuery

func BuildQuery(m map[string]interface{}) (q string)

BuildQuery query parse

func ClimbStairs3

func ClimbStairs3(x int) int

ClimbStairs3 chatgpt generated code Method: ClimbStairs3 Language: Go Description: When climbing stairs, you can walk one, two or three steps at a time. How many ways are there in total? Parameters: This method receives the following parameters: x: total number of steps Output: Number of ways to climb the stairs

Example
n := ClimbStairs3(22)

fmt.Println(n)
Output:

410744

func Contains

func Contains(slice interface{}, item interface{}) bool

func CountWeekday

func CountWeekday(start, end time.Time, day time.Weekday) int
Example
c1 := CountWeekday(time.Unix(time.Now().Unix()-86400*14, 0), time.Now(), time.Tuesday)
fmt.Println(c1)
Output:

2

func CsvWrite

func CsvWrite(filename string, records [][]string) (err error)

func DayBeginAt

func DayBeginAt(t time.Time) int64

DayBeginAt unix timestamp of zero o'clock of the day

Example

1693193334 2023-08-28 11:28:54 1693152000 2023-08-28 00:00:00

t := time.Unix(1693193334, 0)
u := DayBeginAt(t)

fmt.Println(time.Unix(u, 0).Format(time.TimeOnly))
Output:

00:00:00

func DayEndedAt

func DayEndedAt(t time.Time) int64

DayEndedAt unix timestamp of 23:59:59 o'clock of the day

Example
tm := time.Unix(1693193334, 0)
tme := DayEndedAt(tm)
fmt.Println(time.Unix(tme, 0).Format(time.TimeOnly))
Output:

23:59:59

func Delete

func Delete(url string, rq []byte, headers map[string]string, timeout time.Duration) (rp []byte, err error)

Delete HTTP DELETE

func FibonacciDP

func FibonacciDP(n int) int

func FibonacciRecursion

func FibonacciRecursion(n int) int
Example
n1 := FibonacciRecursion(22)
n2 := FibonacciDP(22)

fmt.Println(n1, n1 == n2)
Output:

17711 true

func FileCreate

func FileCreate(filename string) (*os.File, error)

func FileExists

func FileExists(filename string) (y bool, err error)

func Get

func Get(url string, params map[string]interface{}, headers map[string]string, timeout time.Duration) (ret []byte, err error)

Get Http Get query array: convert map["name1"]["v1", "v2"] to name1[]=v1&name1[]=v2

Example
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello, Get")
}))
defer ts.Close()

res, err := Get(ts.URL, nil, nil, 10*time.Second)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%s", string(res))
Output:

Hello, Get

func GinReverseProxy

func GinReverseProxy(c *gin.Context, remoteUrl string) error

GinReverseProxy gin reverse proxy

Example
engine := gin.New()

addr := fmt.Sprintf("0.0.0.0:8080")

engine.Any("/reverseProxy/:proxyPath", func(c *gin.Context) {
	remoteUrl := fmt.Sprintf("https://remoteServer.com/%s", c.Param("proxyPath"))
	err := GinReverseProxy(c, remoteUrl)

	if err != nil {
		log.Fatal(err)
	}
})

err := engine.Run(addr)

if err != nil {
	log.Fatal(err)
}
Output:

func GinRun

func GinRun(host, port string) error

func IdMask

func IdMask(id int64) (str string)

IdMask Generate irregular, reversible masks

func IdUnmask

func IdUnmask(mask string) (id int64)
Example
package main

import (
	"fmt"
	"github.com/lleiiell/goist"
)

func main() {
	fmt.Println(goist.IdUnmask("1clb"))
	fmt.Println(goist.IdUnmask("rr5fk"))
	fmt.Println(goist.IdUnmask("1djlwzxe5tj1a4qw"))
}
Output:

1
999
6521156348675224222

func InsertionSort

func InsertionSort(arr []int)
Example
nums := []int{22, 11, 33, 55, 44, 66}
fmt.Println(nums)

InsertionSort(nums)
fmt.Println(nums)
Output:

[22 11 33 55 44 66]
[11 22 33 44 55 66]

func IsAscii

func IsAscii(s string) bool

func IsJsonEmpty

func IsJsonEmpty(data []byte) bool

func IsNumber

func IsNumber(x interface{}) (y bool)
Example
fmt.Println(IsNumber("a"), IsNumber([]interface{}{"a", 1}))

fmt.Println(IsNumber(1), IsNumber(-1), IsNumber(1.23),
	IsNumber(complex(1, 2)), IsNumber(1+2i))
Output:

false false
true true true true true

func IsStrEmpty

func IsStrEmpty(str string) bool

func MD5

func MD5(str string) string
Example
package main

import (
	"fmt"
	"github.com/lleiiell/goist"
)

func main() {
	fmt.Println(goist.MD5("hello"))
}
Output:

5d41402abc4b2a76b9719d911017c592

func PathClean

func PathClean(dir string) (err error)

func Post

func Post(url string, rq []byte, headers map[string]string, timeout time.Duration) (rp []byte, err error)

Post HTTP POST

func Put

func Put(url string, rq []byte, headers map[string]string, timeout time.Duration) (rp []byte, err error)

Put HTTP PUT

func QuickSort

func QuickSort(nums []int) []int

QuickSort The efficiency of the quicksort algorithm is related to the choice of pivot. If the pivot selected each time is exactly the median of the array, then the time complexity of the algorithm is O(n log n). If the pivot selected each time happens to be the minimum or maximum value of the array, then the time complexity of the algorithm is O(n^2), and the efficiency is low.

Example
nums := []int{22, 11, 33, 55, 44, 66}

nums2 := QuickSort(nums)
fmt.Println(nums2)
Output:

[11 22 33 44 55 66]

func Rand

func Rand() *rand.Rand

func RandStr

func RandStr(n int) string

RandStr random string n custom length

func Retry

func Retry(attempts int, sleep time.Duration, f func() error) error

func SliceIntDiff2Right

func SliceIntDiff2Right(a, b []int) (c []int)

SliceIntDiff2Right returns the elements in `a` that aren't in `b`.

Example
s1 := []int{1, 2, 3}
s2 := []int{2, 4, 5}

fmt.Println(SliceIntDiff2Right(s1, s2))
Output:

[1 3]

func SliceRandOne

func SliceRandOne(sl interface{}) (item interface{})

func Struct2Map

func Struct2Map(in interface{}) (out map[string]interface{}, err error)
Example
st := struct {
	Name string `json:"name,omitempty"`
	True bool   `json:"true"`
}{
	"till",
	true,
}

// m, err := Struct2Map(st)
// fmt.Println(m["name"], m["true"], err)
// Output: till true <nil>

fmt.Println(Struct2Map(st))
Output:

map[name:till true:true] <nil>

func Struct2MapMarshal

func Struct2MapMarshal(st interface{}) (m map[string]interface{}, err error)

func Struct2Str

func Struct2Str(st interface{}, tag, sep string) (s string, err error)
Example
st := struct {
	Name  string `json:"name,omitempty"`
	True  bool   `json:"true"`
	Title string
}{
	"till",
	true,
	"title",
}

// m, err := Struct2Map(st)
// fmt.Println(m["name"], m["true"], err)
// Output: till true <nil>

fmt.Println(Struct2Str(st, "", ""))
Output:

name,true,Title <nil>

func Struct2StrAndWrap

func Struct2StrAndWrap(st interface{}, tag, sep, wrap string) (s string, err error)
Example
st := struct {
	Name  string `json:"name,omitempty"`
	True  bool   `json:"true"`
	Title string
}{
	"till",
	true,
	"title",
}

fmt.Println(Struct2StrAndWrap(st, "", "", "`"))
Output:

`name`,`true`,`Title` <nil>

func Time2now

func Time2now(t time.Time) string
Example
fmt.Println(Time2now(time.Unix(time.Now().Unix()-5, 0)))
fmt.Println(Time2now(time.Unix(time.Now().Unix()-60*2-5, 0)))
fmt.Println(Time2now(time.Unix(time.Now().Unix()-3600*2-5, 0)))
fmt.Println(Time2now(time.Unix(time.Now().Unix()-86400*2-5, 0)))
Output:

刚刚
2分钟
2小时
2天

func Time2short

func Time2short(d time.Duration) string

Time2short short string format

Example
fmt.Println(Time2short(10236 * time.Millisecond))
fmt.Println(Time2short(1023600 * time.Millisecond))
fmt.Println(Time2short(10236000 * time.Millisecond))
Output:

10.24s
17.06m
2.84h

func TimeDiffDays

func TimeDiffDays(first time.Time, second time.Time) int

TimeDiffDays number of days between given time

Example
t0, _ := time.Parse(time.DateTime, "2023-08-28 00:10:00")
t1, _ := time.Parse(time.DateTime, "2023-08-28 23:00:00")
t2, _ := time.Parse(time.DateTime, "2023-08-29 00:10:00")
t3, _ := time.Parse(time.DateTime, "2023-08-29 23:59:59")
t4, _ := time.Parse(time.DateTime, "2022-08-29 23:59:59")

fmt.Println(TimeDiffDays(t1, t0), TimeDiffDays(t2, t0), TimeDiffDays(t3, t1),
	TimeDiffDays(t4, t0))
Output:

0 1 1 364

func TimeIsLeapYear

func TimeIsLeapYear(t time.Time) bool
Example
t1, _ := time.Parse("2006-01-02 15", "2000-09-01 1")
t2, _ := time.Parse("2006-01-02 15", "1900-09-03 23")
t3, _ := time.Parse("2006-01-02 15", "2024-08-28 23")

fmt.Println(TimeIsLeapYear(t1), TimeIsLeapYear(t2), TimeIsLeapYear(t3))
Output:

true false true

func TimeIsSameDay

func TimeIsSameDay(first time.Time, second time.Time) bool
Example
t0, _ := time.Parse(time.DateTime, "2023-08-28 00:10:00")
t1, _ := time.Parse(time.DateTime, "2023-08-28 23:00:00")
t2, _ := time.Parse(time.DateTime, "2023-08-29 00:10:00")
t3, _ := time.Parse(time.DateTime, "2023-08-29 23:59:59")
t4, _ := time.Parse(time.DateTime, "2022-08-29 23:59:59")

fmt.Println(TimeIsSameDay(t0, t1), TimeIsSameDay(t0, t2), TimeIsSameDay(t3, t4))
Output:

true false false

func ToInterfaceSlice

func ToInterfaceSlice(sl interface{}) (isl []interface{})
Example
s1 := []int{1, 2, 3}
is1 := ToInterfaceSlice(s1)
fmt.Println(reflect.ValueOf(is1).Type(), reflect.ValueOf(s1).Type())

sl2 := []string{"a", "b", "c"}
isl2 := ToInterfaceSlice(sl2)
fmt.Println(reflect.ValueOf(isl2).Type(), reflect.ValueOf(sl2).Type())
Output:

[]interface {} []int
[]interface {} []string

func Token

func Token() string

Token generate token

func Unique

func Unique(slicePtr interface{})

func Uuid22

func Uuid22() string

Uuid22 uuid of length 22

func Uuid32

func Uuid32() string

Uuid32 uuid without dash

func UuidSimple

func UuidSimple() string

UuidSimple uuid without special characters

func WriteBin

func WriteBin(filename string, data interface{}) (err error)

Types

type Err

type Err struct {
	ErrCode interface{}
	ErrMsg  interface{}
}

func (Err) Error

func (e Err) Error() string
Example
e := func() error {
	return Err{
		ErrCode: 123,
		ErrMsg:  "test err",
	}
}()

ee := e.(Err)

fmt.Println(ee.Error())
Output:

ErrCode: 123; ErrMsg: test err

type RoundRobinScheduler

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

func (*RoundRobinScheduler) Add

func (r *RoundRobinScheduler) Add(item RrItem)

func (*RoundRobinScheduler) Next

func (r *RoundRobinScheduler) Next() RrItem

func (*RoundRobinScheduler) Remove

func (r *RoundRobinScheduler) Remove(item RrItem)

type RrItem

type RrItem struct {
	Id int64
}

Jump to

Keyboard shortcuts

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