/lancet

A comprehensive, efficient, and reusable util function library of go.

Primary LanguageGoMIT LicenseMIT


Go version Release GoDoc Go Report Card test codecov License

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.
  • 💪 300+ go util functions, support string, slice, datetime, net, crypt...
  • 💅 Only depend on the go standard library.
  • 🌍 Unit test for every exported function.

Installation

Note:

  1. 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/duke-git/lancet/v2 // will install latest version of v2.x.x
  1. For users who use version below go1.18, you should install v1.x.x. The latest of v1.x.x is v1.3.5.
go get github.com/duke-git/lancet@v1.3.5 // 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

1. Algorithm package implements some basic algorithm. eg. sort, search.

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] [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. Concurrency package contain some functions to support concurrent programming. eg, goroutine, channel, async.

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 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]

3. Condition package contains some functions for conditional judgment. eg. And, Or, TernaryOperator...

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. [doc] [play]

4. Convertor package contains some functions for data convertion.

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]
  • 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]

5. Cryptor package is for data encryption and decryption.

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]
  • 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]
  • HmacSha1 : return the hmac hash of string use sha1. [doc] [play]
  • HmacSha256 : return the hmac hash of string use sha256. [doc] [play]
  • HmacSha512 : return the hmac hash of string use sha512. [doc] [play]
  • Md5String : return the md5 value of string. [doc] [play]
  • Md5File : return the md5 value of file. [doc]
  • Sha1 : 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]
  • Sha512 : return the sha512 value (SHA-512 hash algorithm) of 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]

6. Datetime package supports date and time format and compare.

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]
  • 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]
  • 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]

7. Datastructure package constains some common data structure. eg. list, linklist, stack, queue, set, tree, graph.

import list "github.com/duke-git/lancet/v2/datastructure/list"
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"

Structure list:

  • List : a linear table, implemented with slice. [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]

8. Fileutil package implements some basic functions for file operations.

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]
  • 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 zip file. [doc] [play]
  • UnZip : unzip the zip file and save it to dest path. [doc] [play]

9. Formatter contains some functions for data formatting.

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 symbol char. [doc] [play]

10. Function package can control the flow of function execution and support part of functional programming

import "github.com/duke-git/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]

11. Maputil package includes some functions to manipulate map.

import "github.com/duke-git/lancet/v2/maputil"

Function list:

  • 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]
  • 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]
  • 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]
  • IsDisjoint : check two map are disjoint if they have no keys in common. [doc] [play]

12. Mathutil package implements some functions for math calculation.

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. [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]

13. Netutil package contains functions to get net information and send http request.

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]
  • 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 get http request. [doc]
  • HttpDeletedeprecated : send delete http request. [doc]
  • HttpPostdeprecated : send post http request. [doc]
  • HttpPutdeprecated : send put http request. [doc]
  • HttpPatchdeprecated : send patch http request. [doc]
  • ParseHttpResponse : decode http response into target object. [doc]

14. Random package implements some basic functions to generate random int and string.

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]
  • UUIdV4 : generate a random UUID of version 4 according to RFC 4122. [doc] [play]

15. Retry package is for executing a function repeatedly until it was successful or canceled by the context.

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]

16. Slice contains some functions to manipulate slice.

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]
  • 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 : creates a slice with n elements dropped from the beginning when n > 0, or n elements dropped from the ending when n < 0. [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]
  • Find : iterates over elements of slice, returning the first one that passes a truth test on predicate function. [doc] [play]
  • FindLast : return the last item 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]
  • ForEach : iterates over elements of slice and invokes function for each element. [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]
  • Reduce : creates an slice of values by running each element of slice thru iteratee function. [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]
  • 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]

17. Strutil package contains some functions to manipulate string.

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]
  • Capitalize : converts the first character of source string to upper case and the remaining to lower case. [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]
  • 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]

19. System package contain some functions about os, runtime, shell command.

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. [doc] [play]
  • GetOsBits : return current os bits (32 or 64). [doc] [play]

19. Validator package contains some functions for data validation.

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]
  • 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]
  • IsFloatStr : check if the string can convert to a float. [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]
  • 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]

20. xerror package implements helpers for errors.

import "github.com/duke-git/lancet/v2/xerror"

Function list:

  • Unwrap : check if err is nil then it returns a valid value. If err is not nil, Unwrap panics with err. [doc] [play]

How to Contribute

I really appreciate any code commits which make lancet lib powerful. Please follow the rules below to create your pull request.

  1. Fork the repository.
  2. Create your feature branch.
  3. Commit your changes.
  4. Push to the branch
  5. Create new pull request.