Lancet is a comprehensive, efficient, and reusable util function library of go. Inspired by the java apache common package and lodash.js.
English | 简体中文
Feature
- 👏 Comprehensive, efficient and reusable.
- 💪 600+ 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 was rewriten with generics of go1.18.
go get github.com/skirbyte/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.1.
go get github.com/skirbyte/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/skirbyte/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/skirbyte/lancet/v2/strutil"
)
func main() {
s := "hello"
rs := strutil.Reverse(s)
fmt.Println(rs) //olleh
}
Documentation
Index
1. Algorithm package implements some basic algorithm. eg. sort, search. index
import "github.com/skirbyte/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]
[play]
- ShellSort : sorts slice with shell sort algorithm, will change the original slice.
[doc]
[play]
- BinarySearch : returns the index of target within a sorted slice, use binary search (recursive call itself).
[doc]
[play]
- BinaryIterativeSearch : returns the index of target within a sorted slice, use binary search (no recursive).
[doc]
[play]
- LinearSearch : returns the index of target in slice base on equal function.
[doc]
[play]
- LRUCache : implements memory cache with lru algorithm.
[doc]
[play]
2. Compare package provides a lightweight comparison function on any type. index
import "github.com/skirbyte/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]
3. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async. index
import "github.com/skirbyte/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 repeatly until cancel the context.
[doc]
[play]
- RepeatFn : create a channel, excutes fn repeatly, and put the result into the channel, until close context.
[doc]
[play]
- Take : create a channel whose values are taken from another channel with limit number.
[doc]
[play]
- Tee : split one chanel into two channels, until cancel the context.
[doc]
[play]
4. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator... index
import "github.com/skirbyte/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.
[doc]
[play]
5. Convertor package contains some functions for data convertion. index
import "github.com/skirbyte/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]
- ToInt : convert value to int64 value, if input is not numerical, return 0 and error.
[doc]
[play]
- ToJson : convert value to a json string.
[doc]
[play]
- ToMap : convert a slice of structs to a map based on iteratee function.
[doc]
[play]
- ToPointer : return a pointer of passed value.
[doc]
[play]
- ToString : convert value to string.
[doc]
[play]
- StructToMap : convert struct to map, only convert exported struct field.
[doc]
[play]
- MapToSlice : convert map to slice based on iteratee function.
[doc]
[play]
- EncodeByte : encode data to byte slice.
[doc]
[play]
- DecodeByte : decode byte slice data to target object.
[doc]
[play]
- DeepClone : creates a deep copy of passed item, can't clone unexported field of struct.
[doc]
[play]
- CopyProperties : copies each field from the source struct into the destination struct.
[doc]
[play]
- ToInterface : converts reflect value to its interface type.
[doc]
[play]
- Utf8ToGbk : converts utf8 encoding data to GBK encoding data
[doc]
[play]
- GbkToUtf8 : converts GBK encoding data to utf8 encoding data.
[doc]
[play]
6. Cryptor package is for data encryption and decryption. index
import "github.com/skirbyte/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]
- AesOfbEncrypt : encrypt byte slice data with key use AES OFB algorithm.
[doc]
[play]
- AesOfbDecrypt : decrypt byte slice data with key use AES OFB algorithm.
[doc]
[play]
- Base64StdEncode : encode string with base64 encoding.
[doc]
[play]
- Base64StdDecode : decode string with base64 encoding.
[doc]
[play]
- DesEcbEncrypt : encrypt byte slice data with key use DES ECB algorithm.
[doc]
[play]
- DesEcbDecrypt : decrypt byte slice data with key use DES ECB algorithm.
[doc]
[play]
- DesCbcEncrypt : encrypt byte slice data with key use DES CBC algorithm.
[doc]
[play]
- DesCbcDecrypt : decrypt byte slice data with key use DES CBC algorithm.
[doc]
[play]
- DesCtrCrypt : encrypt/decrypt byte slice data with key use DES CRY algorithm.
[doc]
[play]
- DesCfbEncrypt : encrypt byte slice data with key use DES CFB algorithm.
[doc]
[play]
- DesCfbDecrypt : decrypt byte slice data with key use DES CFB algorithm.
[doc]
[play]
- DesOfbEncrypt : encrypt byte slice data with key use DES OFB algorithm.
[doc]
[play]
- DesOfbDecrypt : decrypt byte slice data with key use DES OFB algorithm.
[doc]
[play]
- HmacMd5 : return the md5 hmac hash of string.
[doc]
[play]
- HmacMd5WithBase64 : return the md5 hmac hash of base64 string.
[doc]
- HmacSha1 : return the hmac hash of string use sha1.
[doc]
[play]
- HmacSha1WithBase64 : return the hmac hash of string use sha1 with base64.
[doc]
[play]
- HmacSha256 : return the hmac hash of string use sha256.
[doc]
[play]
- HmacSha256WithBase64 : return the hmac hash of string use sha256 with base64.
[doc]
[play]
- HmacSha512 : return the hmac hash of string use sha512.
[doc]
[play]
- HmacSha512WithBase64 : return the hmac hash of string use sha512 with base64.
[doc]
[play]
- Md5Byte : return the md5 string of byte slice.
[doc]
[play]
- Md5ByteWithBase64 : return the md5 string of byte slice with base64.
[doc]
[play]
- Md5String : return the md5 value of string.
[doc]
[play]
- Md5StringWithBase64 : return the md5 value of string with base64.
[doc]
[play]
- Md5File : return the md5 value of file.
[doc]
- Sha1 : return the sha1 value (SHA-1 hash algorithm) of base64 string.
[doc]
[play]
- Sha1WithBase64 : return the sha1 value (SHA-1 hash algorithm) of string.
[doc]
[play]
- Sha256 : return the sha256 value (SHA-256 hash algorithm) of string.
[doc]
[play]
- Sha256WithBase64 : return the sha256 value (SHA256 hash algorithm) of base64 string.
[doc]
[play]
- Sha512 : return the sha512 value (SHA-512 hash algorithm) of string.
[doc]
[play]
- Sha512WithBase64 : return the sha512 value (SHA-512 hash algorithm) of base64 string.
[doc]
[play]
- GenerateRsaKey : create rsa private and public pemo file.
[doc]
[play]
- RsaEncrypt : encrypt data with ras algorithm.
[doc]
[play]
- RsaDecrypt : decrypt data with ras algorithm.
[doc]
[play]
7. Datetime package supports date and time format and compare. index
import "github.com/skirbyte/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]
- AddYear : add or sub year to the time.
[doc]
[play]
- BeginOfMinute : return the date time at the begin of minute of specific date.
[doc]
[play]
- BeginOfHour : return the date time at the begin of hour of specific date.
[doc]
[play]
- BeginOfDay : return the date time at the begin of day of specific date.
[doc]
[play]
- BeginOfWeek : return the date time at the begin of week of specific date.
[doc]
[play]
- BeginOfMonth : return the date time at the begin of month of specific date.
[doc]
[play]
- BeginOfYear : return the date time at the begin of year of specific date.
[doc]
[play]
- EndOfMinute : return the date time at the end of minute of specific date.
[doc]
[play]
- EndOfHour : return the date time at the end of hour of specific date.
[doc]
[play]
- EndOfDay : return the date time at the end of day of specific date.
[doc]
[play]
- EndOfWeek : return the date time at the end of week of specific date.
[doc]
[play]
- EndOfMonth : return the date time at the end of month of specific date.
[doc]
[play]
- EndOfYear : return the date time at the end of year of specific date.
[doc]
[play]
- GetNowDate : return format yyyy-mm-dd of current date.
[doc]
[play]
- GetNowTime : return format hh-mm-ss of current time.
[doc]
[play]
- GetNowDateTime : return format yyyy-mm-dd hh-mm-ss of current datetime.
[doc]
[play]
- GetTodayStartTime : return the start time of today, format: yyyy-mm-dd 00:00:00.
[doc]
[play]
- GetTodayEndTime : return the end time of today, format: yyyy-mm-dd 23:59:59.
[doc]
[play]
- GetZeroHourTimestamp : return timestamp of zero hour (timestamp of 00:00).
[doc]
[play]
- GetNightTimestamp : return timestamp of zero hour (timestamp of 23:59).
[doc]
[play]
- FormatTimeToStr : convert time to string.
[doc]
[play]
- FormatStrToTime : convert string to time.
[doc]
[play]
- NewUnix : return unix timestamp of specific time.
[doc]
[play]
- NewUnixNow : return unix timestamp of current time.
[doc]
[play]
- NewFormat : return unix timestamp of specific time string, t should be "yyyy-mm-dd hh:mm:ss".
[doc]
[play]
- NewISO8601 : return unix timestamp of specific iso8601 time string.
[doc]
[play]
- ToUnix : return unix timestamp.
[doc]
[play]
- ToFormat : return the time string 'yyyy-mm-dd hh:mm:ss' of unix time.
[doc]
[play]
- ToFormatForTpl : return the time string which format is specific tpl.
[doc]
[play]
- ToIso8601 : return iso8601 time string.
[doc]
[play]
- IsLeapYear : check if param
year
is leap year or not.
[doc]
[play]
- BetweenSeconds : returns the number of seconds between two times.
[doc]
[play]
- DayOfYear : returns which day of the year the parameter date
t
is.
[doc]
[play]
- IsWeekend : checks if passed time is weekend or not.
[doc]
[play]
- NowDateOrTime : returns current datetime with specific format and timezone.
[doc]
[play]
- Timestamp : returns current second timestamp.
[doc]
- TimestampMilli : returns current mill second timestamp.
[doc]
[play]
- TimestampMicro : returns current micro second timestamp.
[doc]
[play]
- TimestampNano : returns current nano second timestamp.
[doc]
[play]
8. Datastructure package constains some common data structure. eg. list, linklist, stack, queue, set, tree, graph. index
import list "github.com/skirbyte/lancet/v2/datastructure/list"
import copyonwritelist "github.com/skirbyte/lancet/v2/datastructure/copyonwritelist"
import link "github.com/skirbyte/lancet/v2/datastructure/link"
import stack "github.com/skirbyte/lancet/v2/datastructure/stack"
import queue "github.com/skirbyte/lancet/v2/datastructure/queue"
import set "github.com/skirbyte/lancet/v2/datastructure/set"
import tree "github.com/skirbyte/lancet/v2/datastructure/tree"
import heap "github.com/skirbyte/lancet/v2/datastructure/heap"
import hashmap "github.com/skirbyte/lancet/v2/datastructure/hashmap"
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]
9. Fileutil package implements some basic functions for file operations. index
import "github.com/skirbyte/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]
- 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]
[play]
- IsLink : checks if a file is symbol link or not.
[doc]
[play]
- IsDir : checks if the path is directory or not.
[doc]
[play]
- ListFileNames : return all file names in the path.
[doc]
[play]
- RemoveFile : remove file, param should be file path.
[doc]
[play]
- ReadFileToString : return string of file content.
[doc]
[play]
- ReadFileByLine : read file line by line, return string slice of file content.
[doc]
[play]
- Zip : create a zip file of fpath, fpath could be a file or a directory.
[doc]
[play]
- ZipAppendEntry : append a single file or directory by fpath to an existing zip file.
[doc]
- UnZip : unzip the zip file and save it to dest path.
[doc]
[play]
- CurrentPath : return current absolute path.
[doc]
[play]
- IsZipFile : checks if file is zip file or not.
[doc]
[play]
- FileSize : return file size in bytes.
[doc]
[play]
- MTime : return file modified time(unix timestamp).
[doc]
[play]
- Sha : return file sha value.
[doc]
[play]
- ReadCsvFile : read file content into slice.
[doc]
[play]
- WriteCsvFile : write content to target csv file.
[doc]
[play]
- WriteBytesToFile : write bytes to target file.
[doc]
[play]
- WriteStringToFile : write string to target file.
[doc]
[play]
import "github.com/skirbyte/lancet/v2/formatter"
Function list:
- Comma : add comma to a number value by every 3 numbers from right, ahead by 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]
[play]
11. Function package can control the flow of function execution and support part of functional programming. index
import "github.com/skirbyte/lancet/v2/function"
Function list:
- After : return a function that invokes passed funcation once the returned function is called more than n times.
[doc]
[play]
- Before : return a function that invokes passed funcation 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]
- Debounced : 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]
- Schedule : invoke function every duration time, util close the returned bool channel.
[doc]
[play]
- Pipeline : takes a list of functions and returns a function whose param will be passed into the functions one by one.
[doc]
[play]
- Watcher : Watcher is used for record code excution time. can start/stop/reset the watch timer. get the elapsed time of function execution.
[doc]
[play]
12. Maputil package includes some functions to manipulate map. index
import "github.com/skirbyte/lancet/v2/maputil"
Function list:
- MapTo : quick map any value to struct or any base type.
[doc]
[play]
- ForEach : executes iteratee funcation 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]
[play]
- OmitByValues : the opposite of FilterByValues. remov all elements whose value are in the give slice.
[doc]
[play]
- Intersect : iterates over maps, return a new map of key and value pairs in all given maps.
[doc]
[play]
- Keys : returns a slice of the map's keys.
[doc]
[play]
- KeysBy : creates a slice whose element is the result of function mapper invoked by every map's key.
[doc]
[play]
- Merge : merge maps, next key will overwrite previous key.
[doc]
[play]
- Minus : creates a map of whose key in mapA but not in mapB.
[doc]
[play]
- Values : returns a slice of the map's values.
[doc]
[play]
- ValuesBy : creates a slice whose element is the result of function mapper invoked by every map's value.
[doc]
[play]
- MapKeys : transforms a map to other type map by manipulating it's keys.
[doc]
[play]
- MapValues : transforms a map to other type map by manipulating it's values.
[doc]
[play]
- Entries : transforms a map into array of key/value pairs.
[doc]
[play]
- FromEntries : creates a map based on a slice of key/value pairs.
[doc]
[play]
- Transform : transform a map to another type map.
[doc]
[play]
- IsDisjoint : check two map are disjoint if they have no keys in common.
[doc]
[play]
- HasKey : checks if map has key or not.
[doc]
[play]
- NewConcurrentMap : creates a ConcurrentMap with specific shard count.
[doc]
[play]
- ConcurrentMap_Set : set the value for a key.
[doc]
[play]
- ConcurrentMap_Get : get the value stored in the map for a key, or nil if no.
[doc]
[play]
- ConcurrentMap_GetOrSet : returns the existing value for the key if present.
[doc]
[play]
- ConcurrentMap_Delete : delete the value for a key.
[doc]
[play]
- ConcurrentMap_GetAndDelete :returns the existing value for the key if present and then delete the value for the key.
[doc]
[play]
- ConcurrentMap_Has : checks if map has the value for a key.
[doc]
[play]
- ConcurrentMap_Range : calls iterator sequentially for each key and value present in each of the shards in the map.
[doc]
[play]
13. Mathutil package implements some functions for math calculation. index
import "github.com/skirbyte/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.
[doc]
[play]
- Percent : calculate the percentage of value to total.
[doc]
[play]
- RoundToFloat : round up to n decimal places for float64.
[doc]
[play]
- RoundToString : round up to n decimal places for float64, return string.
[doc]
[play]
- TruncRound : round off n decimal places for int64.
[doc]
[play]
- Range : Creates a slice of numbers from start with specified count, element step is 1.
[doc]
[play]
- RangeWithStep : Creates a slice of numbers from start to end with specified step.
[doc]
[play]
- AngleToRadian : converts angle value to radian value.
[doc]
[play]
- RadianToAngle : converts radian value to angle value.
[doc]
[play]
- PointDistance : get two points distance.
[doc]
[play]
- IsPrime : checks if number is prime number.
[doc]
[play]
- GCD : return greatest common divisor (GCD) of integers.
[doc]
[play]
- LCM : return Least Common Multiple (LCM) of integers.
[doc]
[play]
- Cos : return the cosine of the radian argument.
[doc]
[play]
- Sin : return the sine of the radian argument.
[doc]
[play]
- Log : returns the logarithm of base n.
[doc]
[play]
- Sum : return sum of passed numbers.
[doc]
[play]
- Abs : returns the absolute value of param nubmer.
[doc]
[play]
14. Netutil package contains functions to get net information and send http request. index
import "github.com/skirbyte/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]
- IsPublicIP : verify a ip is public or not.
[doc]
[play]
- IsInternalIP : verify an ip is intranet or not.
[doc]
[play]
- HttpRequest : a composed http request used for HttpClient send request.
[doc]
[play]
- HttpClient : a http client tool, used for sending http request
[doc]
[play]
- SendRequest : send http request.
[doc]
[play]
- DecodeResponse : decode http response into target object.
[doc]
[play]
- StructToUrlValues : convert struct to url valuse.
[doc]
[play]
- HttpGetdeprecated : send http get request.
[doc]
- HttpDeletedeprecated : send http delete request.
[doc]
- HttpPostdeprecated : send http post request.
[doc]
- HttpPutdeprecated : send http put request.
[doc]
- HttpPatchdeprecated : send http patch request.
[doc]
- ParseHttpResponse : decode http response into target object.
[doc]
- DownloadFile : download the file exist in url to a local file.
[doc]
- UploadFile : upload the file to a server.
[doc]
- IsPingConnected : checks if can ping the specified host or not.
[doc]
[play]
- IsTelnetConnected : checks if can if can telnet the specified host or not.
[doc]
[play]
15. Pointer package contains some util functions to operate go pointer. index
import "github.com/skirbyte/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]
- UnwarpOr : UnwarpOr 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]
16. Random package implements some basic functions to generate random int and string. index
import "github.com/skirbyte/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]
- UUIdV4 : generate a random UUID of version 4 according to RFC 4122.
[doc]
[play]
- RandUniqueIntSlice : generate a slice of random int of length n that do not repeat.
[doc]
[play]
17. Retry package is for executing a function repeatedly until it was successful or canceled by the context. index
import "github.com/skirbyte/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]
18. Slice contains some functions to manipulate slice. index
import "github.com/skirbyte/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]
- Chunk : creates a slice of elements split into groups the length of size.
[doc]
[play]
- Compact : creates an slice with all falsey values removed. The values false, nil, 0, and "" are falsey.
[doc]
[play]
- Concat : creates a new slice concatenating slice with any additional slices.
[doc]
[play]
- Count : returns the number of occurrences of the given item in the slice.
[doc]
[play]
- CountBy : iterates over elements of slice with predicate function, returns the number of all matched elements.
[doc]
[play]
- Difference : creates an slice of whose element in slice but not in compared slice.
[doc]
[play]
- DifferenceBy : accepts iteratee which is invoked for each element of slice and values to generate the criterion by which they're compared.
[doc]
[play]
- DifferenceWith : accepts comparator which is invoked to compare elements of slice to values.
[doc]
[play]
- DeleteAt : delete the element of slice from specific start index to end index - 1.
[doc]
[play]
- Drop : drop n elements from the start of a slice.
[doc]
[play]
- DropRight : drop n elements from the end of a slice.
[doc]
[play]
- DropWhile : drop n elements from the start of a slice while predicate function returns true.
[doc]
[play]
- DropRightWhile : drop n elements from the end of a slice while predicate function returns true.
[doc]
[play]
- Equal : checks if two slices are equal: the same length and all elements' order and value are equal.
[doc]
[play]
- EqualWith : checks if two slices are equal with comparator func.
[doc]
[play]
- Every : return true if all of the values in the slice pass the predicate function.
[doc]
[play]
- Filter : iterates over elements of slice, returning an slice of all elements pass the predicate function.
[doc]
[play]
- FilterMap : returns a slice which apply both filtering and mapping to the given slice.
[doc]
[play]
- Finddeprecated : iterates over elements of slice, returning the first one that passes a truth test on predicate function.
[doc]
[play]
- FindBy : iterates over elements of slice, returning the first one that passes a truth test on predicate function.
[doc]
[play]
- FindLastdeprecated : return the last item that passes a truth test on predicate function.
[doc]
[play]
- FindLastBy : iterates over elements of slice, returning the last one that passes a truth test on predicate function.
[doc]
[play]
- Flatten : flattens slice one level.
[doc]
[play]
- FlattenDeep : flattens slice recursive to one level.
[doc]
[play]
- FlatMap : manipulates a slice and transforms and flattens it to a slice of another type.
[doc]
[play]
- ForEach : iterates over elements of slice and invokes function for each element.
[doc]
[play]
- ForEachWithBreak : iterates over elements of slice and invokes function for each element, when iteratee return false, will break the for each loop.
[doc]
[play]
- GroupBy : iterate over elements of the slice, each element will be group by criteria, returns two slices.
[doc]
[play]
- GroupWith : return a map composed of keys generated from the resultults of running each element of slice thru iteratee.
[doc]
[play]
- IntSlicedeprecated : convert param to int slice.
[doc]
[play]
- InterfaceSlicedeprecated : convert param to interface slice.
[doc]
[play]
- Intersection : creates a slice of unique elements that included by all slices.
[doc]
[play]
- InsertAt : insert the value or other slice into slice at index.
[doc]
[play]
- IndexOf : returns the index at which the first occurrence of an item is found in a slice.
[doc]
[play]
- LastIndexOf : returns the index at which the last occurrence of the item is found in a slice.
[doc]
[play]
- Map : creates an slice of values by running each element of slice thru iteratee function.
[doc]
[play]
- Merge : merge all given slices into one slice.
[doc]
[play]
- Reverse : return slice of element order is reversed to the given slice.
[doc]
[play]
- Reducedeprecated : creates an slice of values by running each element of slice thru iteratee function.(Deprecated: use ReduceBy)
[doc]
[play]
- ReduceBy : produces a value from slice by accumulating the result of each element as passed through the reducer function.
[doc]
[play]
- ReduceRight : ReduceRight is like ReduceBy, but it iterates over elements of slice from right to left.
[doc]
[play]
- Replace : returns a copy of the slice with the first n non-overlapping instances of old replaced by new.
[doc]
[play]
- ReplaceAll : returns a copy of the slice with all non-overlapping instances of old replaced by new.
[doc]
[play]
- Repeat : creates a slice with length n whose elements are passed item.
[doc]
[play]
- Shuffle : shuffle the slice.
[doc]
[play]
- IsAscending : Checks if a slice is ascending order.
[doc]
[play]
- IsDescending : Checks if a slice is descending order.
[doc]
[play]
- IsSorted : Checks if a slice is sorted (ascending or descending).
[doc]
[play]
- IsSortedByKey : Checks if a slice is sorted by iteratee function.
[doc]
[play]
- Sort : sorts a slice of any ordered type(number or string).
[doc]
[play]
- SortBy : sorts the slice in ascending order as determined by the less function.
[doc]
[play]
- SortByFielddeprecated : return sorted slice by specific field.
[doc]
[play]
- Some : return true if any of the values in the list pass the predicate function.
[doc]
[play]
- StringSlicedeprecated : convert param to slice of string.
[doc]
[play]
- SymmetricDifference : the symmetric difference of two slice, also known as the disjunctive union.
[doc]
[play]
- ToSlice : returns a slices of a variable parameter transformation.
[doc]
[play]
- ToSlicePointer : returns a pointer to the slices of a variable parameter transformation.
[doc]
[play]
- Unique : remove duplicate elements in slice.
[doc]
[play]
- UniqueBy : call iteratee func with every item of slice, then remove duplicated.
[doc]
[play]
- Union : creates a slice of unique elements, in order, from all given slices.
[doc]
[play]
- UnionBy : accepts iteratee which is invoked for each element of each slice, then union slice.
[doc]
[play]
- UpdateAt : update the slice element at index.
[doc]
[play]
- Without : creates a slice excluding all given items.
[doc]
[play]
- KeyBy : converts a slice to a map based on a callback function.
[doc]
[play]
- Join : join the slice item with specify separator.
[doc]
[play]
19. Stream package implements a sequence of elements supporting sequential and operations. this package is an experiment to explore if stream in go can work as the way java does. its function is very limited. index
import "github.com/skirbyte/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 generater 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]
[play]
- Filter : returns a stream consisting of the elements of this stream that match the given predicate.
[doc]
[play]
- Map : returns a stream consisting of the elements of this stream that apply the given function to elements of stream.
[doc]
[play]
- Peek : returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
[doc]
[play]
- Skip : returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream.
[doc]
[play]
- Limit : returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.
[doc]
[play]
- Reverse : returns a stream whose elements are reverse order of given stream.
[doc]
[play]
- Range : returns a stream whose elements are in the range from start(included) to end(excluded) original stream.
[doc]
[play]
- Sorted : returns a stream consisting of the elements of this stream, sorted according to the provided less function.
[doc]
[play]
- ForEach : performs an action for each element of this stream.
[doc]
[play]
- Reduce : performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
[doc]
[play]
- FindFirst : returns the first element of this stream and true, or zero value and false if the stream is empty.
[doc]
[play]
- FindLast : returns the last element of this stream and true, or zero value and false if the stream is empty.
[doc]
[play]
- Max : returns the maximum element of this stream according to the provided less function. less fuction: a > b
[doc]
[play]
- Min : returns the minimum element of this stream according to the provided less function. less fuction: a < b
[doc]
[play]
- AllMatch : returns whether all elements of this stream match the provided predicate.
[doc]
[play]
- AnyMatch : returns whether any elements of this stream match the provided predicate.
[doc]
[play]
- NoneMatch : returns whether no elements of this stream match the provided predicate.
[doc]
[play]
- Count : returns the count of elements in the stream.
[doc]
[play]
- ToSlice : returns the elements in the stream.
[doc]
[play]
20. Structs package provides several high level functions to manipulate struct, tag, and field. index
import "github.com/skirbyte/lancet/v2/structs"
Function list:
- New : creates a
Struct
instance.
[doc]
- ToMap : converts a valid struct to a map.
[doc]
- Fields : get all fields of a given struct, that the fields are abstract struct field.
[doc]
- IsStruct : check if the struct is valid.
[doc]
- Tag : get a
Tag
of the Field
, Tag
is a abstract struct field tag
[doc]
- Name : get the field name.
[doc]
- Value : get the
Field
underlying value.
[doc]
- Kind : get the field's kind
[doc]
- IsEmbedded : check if the field is an embedded field.
[doc]
- IsExported : check if the field is exporte
[doc]
- IsZero : check if the field is zero value
[doc]
- IsSlice : check if the field is a slice
[doc]
21. Strutil package contains some functions to manipulate string. index
import "github.com/skirbyte/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]
- Capitalize : converts the first character of source string to upper case and the remaining to lower case.
[doc]
[play]
- ContainsAll : return true if target string contains all the substrings.
[doc]
[play]
- ContainsAny : return true if target string contains any one of the substrings.
[doc]
[play]
- IsString : checks if the parameter value data type is string or not.
[doc]
[play]
- KebabCase : coverts string to kebab-case string.
[doc]
[play]
- UpperKebabCase : coverts string to upper KEBAB-CASE string.
[doc]
[play]
- LowerFirst : converts the first character of string to lower case.
[doc]
[play]
- UpperFirst : converts the first character of string to upper case.
[doc]
[play]
- Pad : pads string on the left and right side if it's shorter than size.
[doc]
[play]
- PadEnd : pads string with given characters on the right side if it's shorter than limit size. Padding characters are truncated if they exceed size.
[doc]
[play]
- PadStart : pads string with given characters on the left side if it's shorter than limit size. Padding characters are truncated if they exceed size.
[doc]
[play]
- Reverse : returns string whose char order is reversed to the given string.
[doc]
[play]
- SnakeCase : coverts string to snake_case string.
[doc]
[play]
- UpperSnakeCase : coverts string to upper SNAKE_CASE string.
[doc]
[play]
- SplitEx : split a given string which can control the result slice contains empty string or not.
[doc]
[play]
- Substring : returns a substring of the specific length starting at the specific offset position.
[doc]
[play]
- Wrap : wrap a string with given string.
[doc]
[play]
- Unwrap : unwrap a given string from anther string. will change source string.
[doc]
[play]
- SplitWords : splits a string into words, word only contains alphabetic characters.
[doc]
[play]
- WordCount : return the number of meaningful word of a string, word only contains alphabetic characters.
[doc]
[play]
- RemoveNonPrintable : remove non-printable characters from a string.
[doc]
[play]
- StringToBytes : converts a string to byte slice without a memory allocation.
[doc]
[play]
- BytesToString : converts a byte slice to string without a memory allocation.
[doc]
[play]
- IsBlank : checks if a string is whitespace or empty.
[doc]
[play]
- HasPrefixAny : checks if a string starts with any of an array of specified strings.
[doc]
[play]
- HasSuffixAny : checks if a string ends with any of an array of specified strings.
[doc]
[play]
- IndexOffset : returns the index of the first instance of substr in string after offsetting the string by
idxFrom
.
[doc]
[play]
- ReplaceWithMap : returns a copy of
str
, which is replaced by a map in unordered way, case-sensitively.
[doc]
[play]
- Trim : strips whitespace (or other characters) from the beginning and end of a string.
[doc]
[play]
- SplitAndTrim : splits string
str
by a string delimiter
to a slice, and calls Trim to every element of slice.
[doc]
[play]
- HideString : Hide some chars in source string with param
replaceChar
.
[doc]
[play]
- RemoveWhiteSpace : remove whitespace characters from a string.
[doc]
[play]
22. System package contain some functions about os, runtime, shell command. index
import "github.com/skirbyte/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.
[doc]
[play]
- GetOsBits : return current os bits (32 or 64).
[doc]
[play]
23. Tuple package implements tuple data type and some operations on it. index
import "github.com/skirbyte/lancet/v2/tuple"
Function list:
- Tuple2 : represents a 2 elemnets 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 elemnets 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.
[doc]
[play]
- Tuple4 : represents a 4 elemnets tuple.
[doc]
[play]
- Tuple4_Unbox : returns values in Tuple4.
[doc]
[play]
- Zip4 : create a slice of Tuple4, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip4 : create a group of slice from a slice of Tuple4.
[doc]
[play]
- Tuple5 : represents a 5 elemnets tuple.
[doc]
[play]
- Tuple5_Unbox : returns values in Tuple4.
[doc]
[play]
- Zip5 : create a slice of Tuple5, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip5 : create a group of slice from a slice of Tuple5.
[doc]
[play]
- Tuple6 : represents a 6 elemnets tuple.
[doc]
[play]
- Tuple6_Unbox : returns values in Tuple6.
[doc]
[play]
- Zip6 : create a slice of Tuple6, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip6 : create a group of slice from a slice of Tuple6.
[doc]
[play]
- Tuple7 : represents a 7 elemnets tuple.
[doc]
[play]
- Tuple7_Unbox : returns values in Tuple7.
[doc]
[play]
- Zip7 : create a slice of Tuple7, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip7 : create a group of slice from a slice of Tuple7.
[doc]
[play]
- Tuple8 : represents a 8 elemnets tuple.
[doc]
[play]
- Tuple8_Unbox : returns values in Tuple8.
[doc]
[play]
- Zip8 : create a slice of Tuple8, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip8 : create a group of slice from a slice of Tuple8.
[doc]
[play]
- Tuple9 : represents a 9 elemnets tuple.
[doc]
[play]
- Tuple9_Unbox : returns values in Tuple9.
[doc]
[play]
- Zip9 : create a slice of Tuple9, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip9 : create a group of slice from a slice of Tuple9.
[doc]
[play]
- Tuple10 : represents a 10 elemnets tuple.
[doc]
[play]
- Tuple10_Unbox : returns values in Tuple10.
[doc]
[play]
- Zip10 : create a slice of Tuple10, whose elements are correspond to the given slice elements.
[doc]
[play]
- Unzip10 : create a group of slice from a slice of Tuple10.
[doc]
[play]
24. Validator package contains some functions for data validation. index
import "github.com/skirbyte/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]
- IsBase64 : check if the string is base64 string.
[doc]
[play]
- IsChineseMobile : check if the string is chinese mobile number.
[doc]
[play]
- IsChineseIdNum : check if the string is chinese id card.
[doc]
[play]
- IsChinesePhone : check if the string is chinese phone number.(xxx-xxxxxxxx or xxxx-xxxxxxx.)
[doc]
[play]
- IsCreditCard : check if the string is credit card.
[doc]
[play]
- IsDns : check if the string is dns.
[doc]
[play]
- IsEmail : check if the string is a email address.
[doc]
[play]
- IsEmptyString : check if the string is empty.
[doc]
[play]
- IsFloat : check if the value is float(float32, float34) or not.
[doc]
[play]
- IsFloatStr : check if the string can convert to a float.
[doc]
[play]
- IsNumber : check if the value is number(integer, float) or not.
[doc]
[play]
- IsNumberStr : check if the string can convert to a number.
[doc]
[play]
- IsJSON : check if the string is valid JSON.
[doc]
[play]
- IsRegexMatch : check if the string match the regexp.
[doc]
[play]
- IsInt : check if the string can convert to a number.
[doc]
[play]
- IsIntStr : check if the string can convert to a integer.
[doc]
[play]
- IsIp : check if the string is ip.
[doc]
[play]
- IsIpV4 : check if the string is ipv4.
[doc]
[play]
- IsIpV6 : check if the string is ipv6.
[doc]
[play]
- IsStrongPassword : check if the string is strong password.
[doc]
[play]
- IsUrl : check if the string is url.
[doc]
[play]
- IsWeakPassword : check if the string is weak password.
[doc]
[play]
- IsZeroValue : check if value is a zero value.
[doc]
[play]
- IsGBK : check if data encoding is gbk.
[doc]
[play]
- IsASCII : checks if string is all ASCII char.
[doc]
[play]
- IsPrintable : checks if string is all printable chars.
[doc]
[play]
25. Xerror package implements helpers for errors. index
import "github.com/skirbyte/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]
- XError_Is : checks if target error is XError and Error.id of two errors are matched.
[doc]
[play]
- XError_Values : returns map of key and value that is set by XError.With function.
[doc]
[play]
- XError_StackTrace : returns stack trace which is compatible with pkg/errors.
[doc]
[play]
- XError_Info : returns information of xerror, which can be printed.
[doc]
[play]
- XError_Error : implements standard error interface.
[doc]
[play]
- TryUnwrap : check if err is nil then it returns a valid value. If err is not nil, TryUnwrap panics with err.
[doc]
[play]
How to Contribute
Hello, I am a software developer and have been engaged in development work for 13 years. Love open source software. And be willing to put in the energy for it. I am the creator of project lancet. Since Lancet was released as open source two years ago, it has been used by more than 1,000 internal and external projects. lancet will always be free for all users. Your support is a powerful encouragement for me to continue my struggle. Thanks! You can use WeChat to scans the following QR code or clicks the following sponsor button to initiate sponsorship.
Donated funds will be used to maintain this website and pay for cloud server costs. Or just buy me a cup of ☕️ when I'm sleepy writing code.
Contributors
Thank you to all the people who contributed to lancet!