Lancet
Lancet is a comprehensive, efficient and reusable library of go language tools. The Lancet was inspired by the Java Apache Common package and Lodash.js.
features
- 👏 comprehensive, efficient and reusable
- 💪 100+ Common go tool functions, supporting string, slice, datetime, NET, crypt…
- 💅 relies only on the GO standard library
- 🌍 100% unit test coverage for all export functions
The installation
go get github.com/duke-git/lancet
Copy the code
usage
The Lancet organizes code in a package structure, which requires importing the package name. For example, if you use string-dependent functions, you need to import the strutil package:
import "github.com/duke-git/lancet/strutil"
Copy the code
example
The string utility function ReverseStr is used as an example to import the strutil package:
package main
import (
"fmt"
"github.com/duke-git/lancet/strutil"
)
func main(a) {
s := "hello"
rs := strutil.ReverseStr(s)
fmt.Println(rs) //olleh
}
Copy the code
The API documentation
1. Convertor Data conversion package
- Conversion functions support conversion between common data types
- Import package: import “github.com/duke-git/lancet/convertor”
package main
import (
"fmt"
"github.com/duke-git/lancet/convertor"
)
func main(a) {
s := "12.3"
f, err := convertor.ToFloat(s)
iferr ! =nil {
fmt.Errorf("error is %s", err.Error())
}
fmt.Println(f) / / 12.3
}
Copy the code
- List of functions:
func ColorHexToRGB(colorHex string) (red, green, blue int)// The color value is hexadecimalrgb
func ColorRGBToHex(red, green, blue int) string/ / color valuesrgbhexadecimal
func ToBool(s string) (bool, error)// The string is converted toBool
func ToBytes(data interface{}) ([]byte, error) //interfaceintobyte slice
func ToChar(s string) []string// String to characterslice
func ToFloat(value interface{}) (float64, error) //interfaceintofloat64
func ToInt(value interface{}) (int64, error) //interfaceintoint64
func ToJson(value interface{}) (string, error) //interfaceintojson string
func ToString(value interface{}) string //interfaceintostring
func StructToMap(value interface{}) (map[string]interface{}, error) //structString into amap, you need to setstruct tag `json`
Copy the code
2. Cryptor encryption and decryption package
- Encryption functions support MD5, HMAC, AES, DES, RAS
- Import package: import “github.com/duke-git/lancet/cryptor”
package main
import (
"fmt"
"github.com/duke-git/lancet/cryptor"
)
func main(a) {
data := "hello"
key := "abcdefghijklmnop"
encrypted := cryptor.AesCbcEncrypt([]byte(data), []byte(key))
decrypted := cryptor.AesCbcDecrypt(encrypted, []byte(key))
fmt.Println(string(decrypted)) // hello
}
Copy the code
- List of functions:
func AesEcbEncrypt(data, key []byte) []byte //AES ECBEncryption mode
func AesEcbDecrypt(encrypted, key []byte) []byte //AES ECBMode to decrypt
func AesCbcEncrypt(data, key []byte) []byte //AES CBCEncryption mode
func AesCbcDecrypt(encrypted, key []byte) []byte //AES CBCMode to decrypt
func AesCtrCrypt(data, key []byte) []byte //AES CTRMode encryption/decryption
func AesCfbEncrypt(data, key []byte) []byte //AES CFBEncryption mode
func AesCfbDecrypt(encrypted, key []byte) []byte //AES CFBMode to decrypt
func AesOfbEncrypt(data, key []byte) []byte //AES OFBEncryption mode
func AesOfbDecrypt(data, key []byte) []byte //AES OFBMode to decrypt
func Base64StdEncode(s string) string //base64coding
func Base64StdDecode(s string) string //base64decoding
func DesCbcEncrypt(data, key []byte) []byte //DES CBCEncryption mode
func DesCbcDecrypt(encrypted, key []byte) []byte //DES CBCMode to decrypt
func DesCtrCrypt(data, key []byte) []byte //DES CTRMode encryption/decryption
func DesCfbEncrypt(data, key []byte) []byte //DES CFBEncryption mode
func DesCfbDecrypt(encrypted, key []byte) []byte //DES CFBMode to decrypt
func DesOfbEncrypt(data, key []byte) []byte //DES OFBEncryption mode
func DesOfbDecrypt(data, key []byte) []byte //DES OFBMode to decrypt
func HmacMd5(data, key string) string/ / to gethmac md5value
func HmacSha1(data, key string) string/ / to gethmac sha1value
func HmacSha256(data, key string) string/ / to gethmac sha256value
func HmacSha512(data, key string) string/ / to gethmac sha512value
func Sha1(data string) string/ / to getsha1value
func Sha256(data string) string/ / to getsha256value
func Sha512(data string) string/ / to getsha512value
func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string)/ / generatedRSAThe private key file
func RsaEncrypt(data []byte, pubKeyFileName string) []byte //RSAencryption
func RsaDecrypt(data []byte, privateKeyFileName string) []byte //RSAdecryption
Copy the code
Datetime Datetime processing package
- Processing date and time
- Import package: import “github.com/duke-git/lancet/datetime”
package main
import (
"fmt"
"github.com/duke-git/lancet/datetime"
)
func main(a) {
now := time.Now()
s := datetime.FormatTimeToStr(now, "yyyy-mm-dd hh:mm:ss")
fmt.Println(s) / / the 2021-11-24 11:16:55
}
Copy the code
- List of functions:
func AddDay(t time.Time, day int64) time.Time// Add or subtract days
func AddHour(t time.Time, hour int64) time.Time// Add or subtract hours
func AddMinute(t time.Time, minute int64) time.Time// Add or subtract minutes
func GetNowDate(a) string// Get the current date formatyyyy-mm-dd
func GetNowTime(a) string// Get the current time formathh:mm:ss
func GetNowDateTime(a) string// Get the current date and time formatyyyy-mm-dd hh:mm:ss
func GetZeroHourTimestamp(a) int64// Get the time stamp of the day (00:00)
func GetNightTimestamp(a) int64// Get time stamp (23:59)
func FormatTimeToStr(t time.Time, format string) string// Time formatting string
func FormatStrToTime(str, format string) time.Time// String is converted to time
Copy the code
4. Fileutil file processing package
- Common functions for file handling
- Import package: import “github.com/duke-git/lancet/fileutil”
package main
import (
"fmt"
"github.com/duke-git/lancet/fileutil"
)
func main(a) {
fmt.Println(fileutil.IsDir(". /")) // true
}
Copy the code
- List of functions:
func IsExist(path string) bool// Check whether the file/directory exists
func CreateFile(path string) bool// Create a file
func IsDir(path string) bool// Check whether it is a directory
func RemoveFile(path string) error// Delete files
func CopyFile(srcFilePath string, dstFilePath string) error// Copy the file
func ListFileNames(path string) ([]string, error)// Lists all file names in the directory
Copy the code
5. Formatter Processing package
- Format the correlation handler
- Import package: import “github.com/duke-git/lancet/formatter”
package main
import (
"fmt"
"github.com/duke-git/lancet/formatter"
)
func main(a) {
fmt.Println(formatter.Comma("12345"."")) // "12,345"
fmt.Println(formatter.Comma(12345.67."Selections")) / / "selections 12345.67"
}
Copy the code
- List of functions:
func Comma(v interface{}, symbol string) string// Use commas to separate numbers/strings at 3-digit intervals
Copy the code
6. Netutil Network processing package
- Handle FUNCTIONS related to IP, HTTP requests
- Import package: import “github.com/duke-git/lancet/netutil”
- HTTP params: Header, Query String, body, httpClient
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/duke-git/lancet/netutil"
)
func main(a) {
url := "https://gutendex.com/books?"
header := make(map[string]string)
header["Content-Type"] = "application/json"
queryParams := make(map[string]interface{})
queryParams["ids"] = "1"
resp, err := netutil.HttpGet(url, header, queryParams)
iferr ! =nil {
log.Fatal(err)
}
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response: ", resp.StatusCode, string(body))
}
Copy the code
- List of functions:
func GetInternalIp(a) string// Get the interiorip
func GetPublicIpInfo(a) (*PublicIpInfo, error)// Get publicipInformation:country.region.isp.city.lat.lon.ip
func IsPublicIP(IP net.IP) bool/ / determineipPublic or notip
func HttpGet(url string, params ...interface{}) (*http.Response, error) //http getrequest
func HttpPost(url string, params ...interface{}) (*http.Response, error) //http postrequest
func HttpPut(url string, params ...interface{}) (*http.Response, error) //http putrequest
func HttpDelete(url string, params ...interface{}) (*http.Response, error) //http deleterequest
func HttpPatch(url string, params ...interface{}) (*http.Response, error) //http patchrequest
func ConvertMapToQueryString(param map[string]interface{}) string/ / will bemapConverted tourl query string
Copy the code
7. Random Random number processing package
- Generate and process random numbers
- Import package: import “github.com/duke-git/lancet/random”
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/duke-git/lancet/random"
)
func main(a) {
randStr := random.RandString(6)
fmt.Println(randStr)
}
Copy the code
- List of functions:
func RandBytes(length int) []byte// generate random []byte
func RandInt(min, max int) int// generate randomint
func RandString(length int) string// generate randomstring
Copy the code
8. Slice Operation package
- Slice operation related functions
- Import package: import “github.com/duke-git/lancet/slice”
- As go currently has unstable support for the paradigm, the parameters and return values of slice processing function are mostly interface{}. After the paradigm feature is stable, related functions will be reconstructed
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/duke-git/lancet/slice"
)
func main(a) {
nums := []int{1.4.3.4.6.7.3}
uniqueNums, _ := slice.IntSlice(slice.Unique(nums))
fmt.Println(uniqueNums) //[1 4 3 6 7]
}
Copy the code
- List of functions:
func Contain(slice interface{}, value interface{}) bool/ / determinesliceDoes it includevalue
func Chunk(slice []interface{}, size int)[] []interface{} / / share slice
func ConvertSlice(originalSlice interface{}, newSliceType reflect.Type) interface{} // Convert originalSlice to newSliceType
func Difference(slice1, slice2 interface{}) interface{} / / return
func DeleteByIndex(slice interface{}, start int, end ...int) (interface{}, error)// Delete the sectionstarttoendThe value of the position
func Filter(slice, function interface{}) interface{} Func (index int, value interface{}) bool
func IntSlice(slice interface{}) ([]int, error)/ / tointslice
func InterfaceSlice(slice interface{}) []interface{} // convert to interface{} section
func InsertByIndex(slice interface{}, index int, value interface{}) (interface{}, error)// In the sliceindexPosition insertvalue
func Map(slice, function interface{}) interface{} Func (index int, value interface{}) interface{}
func ReverseSlice(slice interface{})// Reverse slice
func Reduce(slice, function, zero interface{}) interface{} Func (index int, value1, value2 interface{}) interface{}
func SortByField(slice interface{}, field string, sortType ...string) error/ / forstructSlice to sort
func StringSlice(slice interface{}) []string/ / tostringslice
func Unique(slice interface{}) interface{} // remove slices
func UpdateByIndex(slice interface{}, index int, value interface{}) (interface{}, error)// In the sliceindexLocation updatevalue
Copy the code
9. Strutil string processing package
- String manipulation related functions
- Import package: import “github.com/duke-git/lancet/strutil”
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/duke-git/lancet/strutil"
)
func main(a) {
str := "Foo-Bar"
camelCaseStr := strutil.CamelCase(str)
fmt.Println(camelCaseStr) //fooBar
}
Copy the code
- List of functions:
func After(s, char string) string// Intercepts the stringcharThe string after the first occurrence
func AfterLast(s, char string) string// Intercepts the stringcharString after last occurrence
func Before(s, char string) string// Intercepts the stringcharThe string before the first occurrence
func BeforeLast(s, char string) string// Intercepts the stringcharThe string before the last occurrence
func CamelCase(s string) string// The string is convertedcameCase,"foo bar"- >"fooBar"
func Capitalize(s string) string// The string is convertedCapitalize,"fOO"- >"Foo"
func IsString(v interface{}) bool// Check if it is a string
func KebabCase(s string) string// The string is convertedKebabCase,"foo_Bar"- >"foo-bar"
func LowerFirst(s string) string// The first character of the string is converted to lowercase
func PadEnd(source string, size int, padStr string) string// Padding at the end of the stringsizeA character
func PadStart(source string, size int, padStr string) string// Padding at the beginning of the stringsizeA character
func ReverseStr(s string) string// String reverse
func SnakeCase(s string) string// The string is convertedSnakeCase,"fooBar"- >"foo_bar"
Copy the code
10. Validator package
- Data verification function
- Import package: import “github.com/duke-git/lancet/validator”
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/duke-git/lancet/validator"
)
func main(a) {
str := "Foo-Bar"
isAlpha := validator.IsAlpha(str)
fmt.Println(isAlpha) //false
}
Copy the code
- List of functions:
func ContainChinese(s string) bool// Check whether the string contains Chinese characters
func IsAlpha(s string) bool// Determine if the string contains only letters
func IsBase64(base64 string) bool// Determine if the string isbase64
func IsChineseMobile(mobileNum string) bool// Check if the string is a mobile phone number
func IsChineseIdNum(id string) bool// Check if the string is an id number
func IsChinesePhone(phone string) bool// Check whether the string is a landline phone number
func IsCreditCard(creditCart string) bool// Check if the string is a credit card
func IsDns(dns string) bool// Check whether the string isDNS
func IsEmail(email string) bool// Check whether the string is a mailbox
func IsEmptyString(s string) bool// Determine if the string is empty
func IsFloatStr(s string) bool// Determine whether the string can be converted tofloat
func IsNumberStr(s string) bool// Determine whether a string can be converted to a number
func IsRegexMatch(s, regex string) bool// Check whether the string ismatchRegular expression
func IsIntStr(s string) bool// Determine whether a string can be converted to an integer
func IsIp(ipstr string) bool// Check whether the string isip
func IsIpV4(ipstr string) bool// Check whether the string isipv4
func IsIpV6(ipstr string) bool// Check whether the string isipv6
func IsStrongPassword(password string, length int) bool// Check whether the string is a strong password (uppercase and lowercase letters + digits + special characters)
func IsWeakPassword(password string) bool// Check if string is weak password (only letters or numbers)
Copy the code