Website | 简体中文
Features
- 👏 Comprehensive, efficient and reusable.
- 💪 700+ go util functions, support string, slice, datetime, net, crypt...
- 💅 Only depends on two kinds of libraries: go standard library and golang.org/x.
- 🌍 Unit test for every exported function.
Installation
Note:
- For users who use go1.18 and above, it is recommended to install lancet v2.x.x. Cause in v2.x.x all functions were rewritten with generics of go1.18.
go get github.com/duke-git/lancet/v2 // will install latest version of v2.x.x
- For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.4.6.
go get github.com/duke-git/lancet // below go1.18, install latest version of v1.x.x
Usage
Lancet organizes the code into package structure, and you need to import the corresponding package name when use it. For example, if you use string-related functions,import the strutil package like below:
import "github.com/duke-git/lancet/v2/strutil"
Example
Here takes the string function Reverse (reverse order string) as an example, and the strutil package needs to be imported.
package main
import (
"fmt"
"github.com/duke-git/lancet/v2/strutil"
)
func main() {
s := "hello"
rs := strutil.Reverse(s)
fmt.Println(rs) //olleh
}
Documentation
Index
import "github.com/duke-git/lancet/v2/algorithm"
Function list:
- BubbleSort : sorts slice with bubble sort algorithm, will change the original slice.
[doc]
[play]
- CountSort : sorts slice with bubble sort algorithm, don't change original slice.
[doc]
[play]
- HeapSort : sorts slice with heap sort algorithm, will change the original slice.
[doc]
[play]
- InsertionSort : sorts slice with insertion sort algorithm, will change the original slice.
[doc]
[play]
- MergeSort : sorts slice with merge sort algorithm, will change the original slice.
[doc]
[play]
- QuickSort : sorts slice with quick sort algorithm, will change the original slice.
[doc]
[play]
- SelectionSort : sorts slice with selection sort algorithm, will change the original slice.
[doc]
[]
import "github.com/duke-git/lancet/v2/compare"
Function list:
- Equal : Checks if two values are equal or not. (check both type and value)
[doc]
[play]
- EqualValue : Checks if two values are equal or not. (check value only)
[doc]
[play]
- LessThan : Checks if value
left less than value right.
[doc]
[play]
- GreaterThan : Checks if value
left greater than value right.
[doc]
[play]
- LessOrEqual : Checks if value
left less than or equal than value right.
[doc]
[play]
- GreaterOrEqual : Checks if value
left less greater or equal than value right.
[doc]
[play]
- InDelta : Checks if two values are equal or not within a delta.
[doc]
import "github.com/duke-git/lancet/v2/concurrency"
Function list:
- NewChannel : create a Channel pointer instance.
[doc]
[play]
- Bridge : link multiply channels into one channel.
[doc]
[play]
- FanIn : merge multiple channels into one channel.
[doc]
[play]
- Generate : creates a channel, then put values into the channel.
[doc]
[play]
- Or : read one or more channels into one channel, will close when any readin channel is closed.
[doc]
[play]
- OrDone : read a channel into another channel, will close until cancel context.
[doc]
[play]
- Repeat : create channel, put values into the channel repeatedly until cancel the context.
[doc]
[play]
import "github.com/duke-git/lancet/v2/condition"
Function list:
- Bool : returns the truthy value of anything.
[doc]
[play]
- And : returns true if both a and b are truthy.
[doc]
[play]
- Or : returns false if neither a nor b is truthy.
[doc]
[play]
- Xor : returns true if a or b but not both is truthy.
[doc]
[play]
- Nor : returns true if neither a nor b is truthy.
[doc]
[play]
- Xnor : returns true if both a and b or neither a nor b are truthy.
[doc]
[play]
- Nand : returns false if both a and b are truthy.
[doc]
[play]
- TernaryOperator : ternary operator.
[]
[]
import "github.com/duke-git/lancet/v2/convertor"
Function list:
- ColorHexToRGB : convert color hex to color rgb.
[doc]
[play]
- ColorRGBToHex : convert rgb color to hex color.
[doc]
[play]
- ToBool : convert string to bool.
[doc]
[play]
- ToBytes : convert value to byte slice.
[doc]
[play]
- ToChar : convert string to char slice.
[doc]
[play]
- ToChannel : convert a collection of elements to a read-only channel.
[doc]
[play]
- ToFloat : convert value to float64, if param is a invalid floatable, will return 0.0 and error.
[doc]
[play]
- : convert value to int64 value, if input is not numerical, return 0 and error.
[]
[]
import "github.com/duke-git/lancet/v2/cryptor"
Function list:
- AesEcbEncrypt : encrypt byte slice data with key use AES ECB algorithm.
[doc]
[play]
- AesEcbDecrypt : decrypt byte slice data with key use AES ECB algorithm.
[doc]
[play]
- AesCbcEncrypt : encrypt byte slice data with key use AES CBC algorithm.
[doc]
[play]
- AesCbcDecrypt : decrypt byte slice data with key use AES CBC algorithm.
[doc]
[play]
- AesCtrCrypt : encrypt/ decrypt byte slice data with key use AES CRC algorithm.
[doc]
[play]
- AesCfbEncrypt : encrypt byte slice data with key use AES CFB algorithm.
[doc]
[play]
- AesCfbDecrypt : decrypt byte slice data with key use AES CFB algorithm.
[doc]
[play]
import "github.com/duke-git/lancet/v2/datetime"
Function list:
- AddDay : add or sub day to the time.
[doc]
[play]
- AddHour : add or sub day to the time.
[doc]
[play]
- AddMinute : add or sub day to the time.
[doc]
[play]
- AddWeek : add or sub week to time.
[doc]
[play]
- AddMonth : add or sub months to time.
[doc]
[play]
- AddYear : add or sub year to the time.
[doc]
[play]
- AddDaySafe : add or sub days to the time and ensure that the returned date does not exceed the valid date of the target year and month.
[doc]
[play]
- AddMonthSafe : add or sub months to the time and ensure that the returned date does not exceed the valid date of the target year and month.
[]
[]
import list "github.com/duke-git/lancet/v2/datastructure/list"
import copyonwritelist "github.com/duke-git/lancet/v2/datastructure/copyonwritelist"
import link "github.com/duke-git/lancet/v2/datastructure/link"
import stack "github.com/duke-git/lancet/v2/datastructure/stack"
import queue "github.com/duke-git/lancet/v2/datastructure/queue"
import set "github.com/duke-git/lancet/v2/datastructure/set"
import tree "github.com/duke-git/lancet/v2/datastructure/tree"
import heap "github.com/duke-git/lancet/v2/datastructure/heap"
import hashmap "github.com/duke-git/lancet/v2/datastructure/hashmap"
import optional "github.com/duke-git/lancet/v2/datastructure/optional"
Structure list:
- List : a linear table, implemented with slice.
[doc]
- CopyOnWriteList : a thread-safe list implementation that uses go slicing as its base.
[doc]
- Link : link list structure, contains singly link and doubly link.
[doc]
- Stack : stack structure(fifo), contains array stack and link stack.
[doc]
- Queue : queue structure(filo), contains array queue, circular queue, link queue and priority queue.
[doc]
- Set : a data container, like slice, but element of set is not duplicate.
[doc]
- Tree : binary search tree structure.
[doc]
- Heap : a binary max heap.
[doc]
- Hashmap : hash map structure.
[doc]
- Optional : Optional container.
[doc]
import "github.com/duke-git/lancet/v2/eventbus"
Function list:
- NewEventBus : Create an EventBus instance.
[doc]
[play]
- Subscribe : subscribes to an event with a specific event topic and listener function.
[doc]
[play]
- Unsubscribe : unsubscribes from an event with a specific event topic and listener function.
[doc]
[play]
- Publish : publishes an event with a specific event topic and data payload.
[doc]
[play]
- ClearListeners : clears all the listeners.
[doc]
[play]
- ClearListenersByTopic : clears all the listeners by topic.
[doc]
[play]
- GetListenersCount : returns the number of listeners for a specific event topic.
[doc]
[play]
import "github.com/duke-git/lancet/v2/enum"
Function list:
- NewItem : Creates a new enum item.
[doc]
[play]
- NewItemsFromPairs : Creates enum items from a slice of Pair structs.
[doc]
[play]
- Value : Returns the value of the enum item.
[doc]
[play]
- Name : Returns the name of the enum item.
[doc]
[play]
- Valid : Checks if the enum item is valid. If a custom check function is provided, it will be used to validate the value.
[doc]
[play]
- MarshalJSON : Implementation of json.Marshaler interface.
[doc]
[play]
- NewRegistry : Creates a new enum registry.
[doc]
[play]
- : Adds enum items to the registry.
[]
[]
import "github.com/duke-git/lancet/v2/fileutil"
Function list:
- ClearFile : write empty string to target file.
[doc]
[play]
- CreateFile : create file in path.
[doc]
[play]
- CreateDir : create directory in absolute path.
[doc]
[play]
- CopyFile : copy src file to dest file.
[doc]
[play]
- CopyDir : copy src directory to dest directory.
[doc]
[play]
- FileMode : return file's mode and permission.
[doc]
[play]
- MiMeType : return file mime type.
[doc]
[play]
- IsExist : checks if a file or directory exists.
[doc]
[]
import "github.com/duke-git/lancet/v2/formatter"
Function list:
- Comma : add comma to a number value by every 3 numbers from right, ahead by a prefix symbol char.
[doc]
[play]
- Pretty : pretty print data to JSON string.
[doc]
[play]
- PrettyToWriter : pretty encode data to writer.
[doc]
[play]
- DecimalBytes : returns a human readable byte size under decimal standard (base 1000).
[doc]
[play]
- BinaryBytes : returns a human-readable byte size under binary standard (base 1024).
[doc]
[play]
- ParseDecimalBytes : return the human readable bytes size string into the amount it represents(base 1000).
[doc]
[play]
- ParseBinaryBytes : return the human readable bytes size string into the amount it represents(base 1024).
[doc]
[]
import "github.com/duke-git/lancet/v2/function"
Function list:
- After : return a function that invokes passed function once the returned function is called more than n times.
[doc]
[play]
- Before : return a function that invokes passed function once the returned function is called less than n times
[doc]
[play]
- CurryFn : make a curry function.
[doc]
[play]
- Compose : compose the functions from right to left.
[doc]
[play]
- Delay : call the function after delayed time.
[doc]
[play]
- Debounceddeprecated : creates a debounced function that delays invoking fn until after wait duration have elapsed since the last time the debounced function was invoked.
[doc]
[play]
- Debounce : creates a debounced version of the provided function.
[doc]
[]
import "github.com/duke-git/lancet/v2/maputil"
Function list:
- MapTo : quick map any value to struct or any base type.
[doc]
[play]
- ForEach : executes iteratee function for every key and value pair in map.
[doc]
[play]
- Filter : iterates over map, return a new map contains all key and value pairs pass the predicate function.
[doc]
[play]
- FilterByKeys : iterates over map, return a new map whose keys are all given keys
[doc]
[play]
- FilterByValues : iterates over map, return a new map whose values are all given values.
[doc]
[play]
- OmitBy : the opposite of Filter, removes all the map elements for which the predicate function returns true.
[doc]
[play]
- OmitByKeys : the opposite of FilterByKeys, extracts all the map elements which keys are not omitted.
[doc]
[]
import "github.com/duke-git/lancet/v2/mathutil"
Function list:
- Average :return average value of numbers.
[doc]
[play]
- Exponent : calculate x^n for int64.
[doc]
[play]
- Fibonacci :calculate fibonacci number before n for int.
[doc]
[play]
- Factorial : calculate x! for uint.
[doc]
[play]
- Max : return maximum value of numbers.
[doc]
[play]
- MaxBy : return the maximum value of a slice using the given comparator function.
[doc]
[play]
- Min : return minimum value of numbers.
[doc]
[play]
- MinBy : return the minimum value of a slice using the given comparator function.
[]
[]
import "github.com/duke-git/lancet/v2/netutil"
Function list:
- ConvertMapToQueryString : convert map to sorted url query string.
[doc]
[play]
- EncodeUrl : encode url(?a=1&b=[2] -> ?a=1&b=%5B2%5D).
[doc]
[play]
- GetInternalIp : return internal ipv4.
[doc]
[play]
- GetIps : return all ipv4 of current system.
[doc]
[play]
- GetMacAddrs : return mac address of current system.
[doc]
[play]
- GetPublicIpInfo : return public ip information.
[doc]
[play]
- GetRequestPublicIp : return the http request public ip.
[doc]
[play]
import "github.com/duke-git/lancet/v2/pointer"
Function list:
- ExtractPointer : return the underlying value by the given interface type.
[doc]
[play]
- Of : return a pointer to the value
v.
[doc]
[play]
- Unwrap : return the value from the pointer.
[doc]
[play]
- UnwrapOr : UnwrapOr returns the value from the pointer or fallback if the pointer is nil.
[doc]
[play]
- UnwarpOrDefault : UnwarpOrDefault returns the value from the pointer or the default value if the pointer is nil.
[doc]
[play]
import "github.com/duke-git/lancet/v2/random"
Function list:
- RandBytes : generate random byte slice.
[doc]
[play]
- RandInt : generate random int number between min and max.
[doc]
[play]
- RandString : generate random string of specific length.
[doc]
[play]
- RandUpper : generate a random upper case string.
[doc]
[play]
- RandLower : generate a random lower case string.
[doc]
[play]
- RandNumeral : generate a random numeral string of specific length.
[doc]
[play]
- RandNumeralOrLetter : generate a random numeral or letter string.
[doc]
[play]
- : generate a random UUID of version 4 according to RFC 4122.
[]
[]
import "github.com/duke-git/lancet/v2/retry"
Function list:
- Context : set retry context config option.
[doc]
[play]
- Retry : executes the retryFunc repeatedly until it was successful or canceled by the context.
[doc]
[play]
- RetryFunc : function that retry executes.
[doc]
[play]
- RetryDuration : set duration of retry
[doc]
[play]
- RetryTimes : set times of retry.
[doc]
[play]
- BackoffStrategy : An interface that defines a method for calculating backoff intervals.
[doc]
- RetryWithCustomBackoff : set abitary custom backoff strategy.
[doc]
[play]
- RetryWithLinearBackoff : set linear strategy backoff.
[doc]
[]
import "github.com/duke-git/lancet/v2/slice"
Function list:
- AppendIfAbsent : if the item is absent,append it to the slice.
[doc]
[play]
- Contain : check if the value is in the slice or not.
[doc]
[play]
- ContainBy : returns true if predicate function return true.
[doc]
[play]
- ContainSubSlice : check if the slice contain a given subslice or not.
[doc]
[play]
- ContainAny : check if the slice contains any element from the targets slice.
[doc]
[play]
- Chunk : creates a slice of elements split into groups the length of size.
[doc]
[play]
- Compact : creates an slice with all falsy values removed. The values false, nil, 0, and "" are falsy.
[doc]
[play]
import "github.com/duke-git/lancet/v2/stream"
Function list:
- Of : creates a stream whose elements are the specified values.
[doc]
[play]
- FromSlice : creates a stream from slice.
[doc]
[play]
- FromChannel : creates a stream from channel.
[doc]
[play]
- FromRange : creates a number stream from start to end. both start and end are included. [start, end]
[doc]
[play]
- Generate : creates a stream where each element is generated by the provided generator function.
[doc]
[play]
- Concat : creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
[doc]
[play]
- Distinct : creates returns a stream that removes the duplicated items.
[doc]
[]
import "github.com/duke-git/lancet/v2/structs"
Function list:
- New : creates a
Struct instance.
[doc]
[play]
- ToMap : converts a valid struct to a map.
[doc]
[play]
- Fields : get all fields of a given struct, that the fields are abstract struct field.
[doc]
[play]
- Field : get an abstract field of a struct by given field name
[doc]
[play]
- IsStruct : check if the struct is valid.
[doc]
[play]
- Tag : get a
Tag of the Field, Tag is a abstract struct field tag.
[doc]
[play]
- Name : get the field name.
[doc]
[play]
import "github.com/duke-git/lancet/v2/strutil"
Function list:
- After : returns the substring after the first occurrence of a specific string in the source string.
[doc]
[play]
- AfterLast : returns the substring after the last occurrence of a specific string in the source string. [doc]
[play]
- Before : returns the substring before the first occurrence of a specific string in the source string.
[doc]
[play]
- BeforeLast : returns the substring before the last occurrence of a specific string in the source string.
[doc]
[play]
- CamelCase : coverts source string to its camelCase string.
[doc]
[play]
- UpperCamelCase : coverts source string to its UpperCamelCase string.
[doc]
[play]
- Capitalize : converts the first character of source string to upper case and the remaining to lower case.
[doc]
[]
import "github.com/duke-git/lancet/v2/system"
Function list:
- IsWindows : check if current os is windows.
[doc]
[play]
- IsLinux : check if current os is linux.
[doc]
[play]
- IsMac : check if current os is macos.
[doc]
[play]
- GetOsEnv : get the value of the environment variable named by the key.
[doc]
[play]
- SetOsEnv : set the value of the environment variable named by the key.
[doc]
[play]
- RemoveOsEnv : remove a single environment variable.
[doc]
[play]
- CompareOsEnv : get env named by the key and compare it with passed env.
[doc]
[play]
- ExecCommand : execute command, return the stdout and stderr string of command, and error if error occurs.
[]
[]
import "github.com/duke-git/lancet/v2/tuple"
Function list:
- Tuple2 : represents a 2 elements tuple.
[doc]
[play]
- Tuple2_Unbox : returns values in Tuple2.
[doc]
[play]
- Zip2 : create a slice of Tuple2, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip2 : create a group of slice from a slice of Tuple2.
[doc]
[play]
- Tuple3 : represents a 3 elements tuple.
[doc]
[play]
- Tuple3_Unbox : returns values in Tuple3.
[doc]
[play]
- Zip3 : create a slice of Tuple3, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip3 : create a group of slice from a slice of Tuple3.
[]
[]
import "github.com/duke-git/lancet/v2/validator"
Function list:
- ContainChinese : check if the string contain mandarin chinese.
[doc]
[play]
- ContainLetter : check if the string contain at least one letter.
[doc]
[play]
- ContainLower : check if the string contain at least one lower case letter a-z.
[doc]
[play]
- ContainUpper : check if the string contain at least one upper case letter A-Z.
[doc]
[play]
- IsAlpha : checks if the string contains only letters (a-zA-Z).
[doc]
[play]
- IsAllUpper : check if the string is all upper case letters A-Z.
[doc]
[play]
- IsAllLower : check if the string is all lower case letters a-z.
[doc]
[play]
import "github.com/duke-git/lancet/v2/xerror"
Function list:
- New : creates a new XError pointer instance with message.
[doc]
[play]
- Wrap : creates a new XError pointer instance based on error object, and add message.
[doc]
[play]
- Unwrap : returns unwrapped XError from err by errors.As. If no XError, returns nil.
[doc]
[play]
- XError_Wrap : creates a new XError and copy message and id to new one.
[doc]
[play]
- XError_Unwrap : Compatible with github.com/pkg/errors.
[doc]
[play]
- XError_With : adds key and value related to the XError object.
[doc]
[play]
- XError_Id : sets XError object id to check equality in XError.Is.
[doc]
[play]
How to Contribute
Contributors
Thank you to all the people who contributed to lancet!
Star History