Golang toolset - String tool, time tool, http tool, etc

Posted by nmal on Fri, 21 Jan 2022 12:35:48 +0100

gotool

gotool is a small and complete tool set of Golang, which mainly refines and integrates the methods commonly used in daily development, avoids repeated wheel making and improves work efficiency. Each method is extracted from the author's work experience and previous projects.

How to use gotool?

install

go get github.com/druidcaesa/gotool

go.mod github.com/druidcaesa/gotool

introduce

import "github.com/druidcaesa/gotool"

StrUtils

golang is a common tool set of string, which basically covers the tools often used in development. At present, it is in the process of improper improvement

gotool.StrUtils.ReplacePlaceholder

func TestStringReplacePlaceholder(t *testing.T) {
s := "you are mine{},I am yours{}"
placeholder, err := gotool.StrUtils.ReplacePlaceholder(s, "only", "All")
if err == nil {
    fmt.Println(placeholder)
    }
}
//out
=== RUN   TestStringReplacePlaceholder
 You are my only one,I am all you have
--- PASS: TestStringReplacePlaceholder (0.00s)
PASS

gotool.StrUtils.RemoveSuffix remove file extension get file name

func TestRemoveSuffix(t *testing.T) {
fullFilename := "test.txt"
suffix, _ := gotool.StrUtils.RemoveSuffix(fullFilename)
fmt.Println(suffix)
fullFilename = "/root/home/test.txt"
suffix, _ = gotool.StrUtils.RemoveSuffix(fullFilename)
fmt.Println(suffix)
}
//out
=== RUN   TestRemoveSuffix
test
test
--- PASS: TestRemoveSuffix (0.00s)
PASS

gotool.StrUtils.GetSuffix get file extension

func TestGetSuffix(t *testing.T) {
fullFilename := "test.txt"
suffix, _ := gotool.StrUtils.GetSuffix(fullFilename)
fmt.Println(suffix)
fullFilename = "/root/home/test.txt"
suffix, _ = gotool.StrUtils.GetSuffix(fullFilename)
fmt.Println(suffix)
}
//out
=== RUN   TestGetSuffix
.txt
.txt
--- PASS: TestGetSuffix (0.00s)
PASS

gotool.StrUtils.HasEmpty determines whether the string is not empty, and returns true if it is empty

func TestHasStr(t *testing.T) {
str := ""
empty := gotool.StrUtils.HasEmpty(str)
fmt.Println(empty)
str = "11111"
empty = gotool.StrUtils.HasEmpty(str)
fmt.Println(empty)
}
//out
=== RUN   TestHasStr
true
false
--- PASS: TestHasStr (0.00s)
PASS

DateUtil

golang is a time operation tool set, which basically covers the tools often used in development. At present, it is in the process of improper improvement

gotool.DateUtil.FormatToString formats the time into a string

func TestFormatToString(t *testing.T) {
now := gotool.DateUtil.Now()
toString := gotool.DateUtil.FormatToString(&now, "YYYY-MM-DD hh:mm:ss")
fmt.Println(toString)
toString = gotool.DateUtil.FormatToString(&now, "YYYYMMDD hhmmss")
fmt.Println(toString)
}
//YYYY MM DD hhmmss can be combined arbitrarily, such as yyyy HH yyyy DD HH: mm
//out
=== RUN   TestFormatToString
2021-07-07 16:13:30
20210707 161330
--- PASS: TestFormatToString (0.00s)
PASS

gotool.DateUtil.IsZero determines whether the time is empty

//Time is null, true, otherwise false
func TestDate_IsZero(t *testing.T) {
t2 := time.Time{}
zero := gotool.DateUtil.IsZero(t2)
fmt.Println(zero)
zero = gotool.DateUtil.IsZero(gotool.DateUtil.Now())
fmt.Println(zero)
}
//out
=== RUN   TestDate_IsZero
true
false
--- PASS: TestDate_IsZero (0.00s)
PASS

gotool.DateUtil.Now gets the current time, which is equivalent to time Now (), in order to unify, this method is also included in the tool

gotool.DateUtil.InterpretStringToTimestamp format string to time type

//Parameter 1: the time string to be formatted parameter 2: the string format should be consistent with that of the string to be formatted 
//For example, 2021-6-4 corresponds to yyyy-mm-dd, 2021.6.4 corresponds to yyyy MM. DD
func TestInterpretStringToTimestamp(t *testing.T) {
timestamp, err := gotool.DateUtil.InterpretStringToTimestamp("2021-05-04 15:12:59", "YYYY-MM-DD hh:mm:ss")
if err != nil {
gotool.Logs.ErrorLog().Println(err.Error())
}
fmt.Println(timestamp)
}
//out
=== RUN   TestInterpretStringToTimestamp
1620112379
--- PASS: TestInterpretStringToTimestamp (0.00s)
PASS

gotool.DateUtil.UnixToTime timestamp to time

func TestUnixToTime(t *testing.T) {
unix := gotool.DateUtil.Now().Unix()
fmt.Println("time stamp----------------------->", unix)
toTime := gotool.DateUtil.UnixToTime(unix)
fmt.Println(toTime)
}
//out
=== RUN   TestUnixToTime
 time stamp-----------------------> 1625645682
2021-07-07 16:14:42 +0800 CST
--- PASS: TestUnixToTime (0.00s)
PASS

gotool.DateUtil.GetWeekDay get day of week

func TestGetWeekDay(t *testing.T) {
now := gotool.DateUtil.Now()
day := gotool.DateUtil.GetWeekDay(now)
fmt.Println("Today is-----------------week", day)
}
//out
=== RUN   TestGetWeekDay
 Today is-----------------Week 3
--- PASS: TestGetWeekDay (0.00s)
PASS

gotool.DateUtil.MinuteAddOrSub,HourAddOrSub,DayAddOrSub time calculation tool

//Time calculation
func TestTimeAddOrSub(t *testing.T) {
now := gotool.DateUtil.Now()
fmt.Println("Now the time is--------------------->", now)
sub := gotool.DateUtil.MinuteAddOrSub(now, 10)
fmt.Println("Minute calculation results-------------------->", sub)
sub = gotool.DateUtil.MinuteAddOrSub(now, -10)
fmt.Println("Minute calculation results-------------------->", sub)
sub = gotool.DateUtil.HourAddOrSub(now, 10)
fmt.Println("Hourly calculation results-------------------->", sub)
sub = gotool.DateUtil.HourAddOrSub(now, -10)
fmt.Println("Hourly calculation results-------------------->", sub)
sub = gotool.DateUtil.DayAddOrSub(now, 10)
fmt.Println("Day calculation results-------------------->", sub)
sub = gotool.DateUtil.DayAddOrSub(now, -10)
fmt.Println("Day calculation results-------------------->", sub)
}
//The current time is ------------------------- > 2021-07-07 11:18:17.8295757 + 0800 CST M = + 0.012278001
//Minute calculation results ---------------------------- 2021-07-07 11:28:17.8295757 + 0800 CST M = + 600.012278001
//Minute calculation results ---------------------------- 2021-07-07 11:08:17.8295757 + 0800 CST M = -599.987721999
//Hourly calculation results ---------------------------- 2021-07-07 21:18:17.8295757 + 0800 CST M = + 36000.012278001
//Hourly calculation results ---------------------------- 2021-07-07 01:18:17.8295757 + 0800 CST M = -35999.987721999
//Day calculation results ---------------------------- 2021-07-17 11:18:17.8295757 + 0800 CST M = + 864000.012278001
//Day calculation results ---------------------------- 2021-06-27 11:18:17.8295757 + 0800 CST M = -863999.987721999

ConvertUtils Gregorian to lunar tools

gotool. ConvertUtils. Gregoriantolunarcalendar, getlunaryeardays, getlunaryeardays

func TestConvertTest(t *testing.T) {
calendar := gotool.ConvertUtils.GregorianToLunarCalendar(2020, 2, 1)
fmt.Println(calendar)
gregorian := gotool.ConvertUtils.LunarToGregorian(calendar[0], calendar[1], calendar[2], false)
fmt.Println(gregorian)
days := gotool.ConvertUtils.GetLunarYearDays(2021)
fmt.Println(days)
}
//[2020 1 8]
//[2020 2 1]
//354

gotool.ConvertUtils.GetSolarMonthDays(2021,7) obtain the number of days in a month in the Gregorian calendar and the number of days in July 2021

gotool.ConvertUtils.IsLeapYear(2021) gets whether a year is a auspicious year. True is false, not true

gotool.ConvertUtils.GetLeapMonth(2021) get leap month of a year

BcryptUtils confidential and decryption tools

gotool.BcryptUtils.Generate encryption processing is mostly used for database storage and use after password encryption, which is irreversible

gotool.BcryptUtils.CompareHash encrypted and unencrypted passwords are mostly used for login authentication

func TestGenerate(t *testing.T) {
//Encrypt
generate := gotool.BcryptUtils.Generate("123456789")
fmt.Println(generate)
//Encryption comparison
hash := gotool.BcryptUtils.CompareHash(generate, "123456789")
fmt.Println(hash)
}
//out
== = RUN   TestGenerate
$2a$10$IACJ6zGuNuzaumrvDz58Q.vJUzz4JGqougYKrdCs48rQYIRjAXcU2
true
--- PASS: TestGenerate (0.11s)
PASS

gotool.BcryptUtils.MD5 md5 encryption

func TestMd5(t *testing.T) {
md5 := gotool.BcryptUtils.MD5("123456789")
fmt.Println(md5)
}
//out
== = RUN   TestMd5
25f9e794323b453885f5181f1b624d0b
--- PASS: TestMd5 (0.00s)
PASS

gotool. BcryptUtils. Genrsakey (get public key and private key),

Rssignwithsha256,

Rsaverysignathsha256 (authentication),

Rsaencrypt (public key encryption),

Rsadecrypt (private key decryption)

func TestRsa(t *testing.T) {
//rsa key file generation
fmt.Println("-------------------------------obtain RSA Public private key-----------------------------------------")
prvKey, pubKey := gotool.BcryptUtils.GenRsaKey()
fmt.Println(string(prvKey))
fmt.Println(string(pubKey))

fmt.Println("-------------------------------Perform signature and verification operations-----------------------------------------")
var data = "I'm encrypted data. Remember me-------------------------------"
fmt.Println("Sign the message...")
signData := gotool.BcryptUtils.RsaSignWithSha256([]byte(data), prvKey)
fmt.Println("Signature information of the message: ", hex.EncodeToString(signData))
fmt.Println("\n Verify signature information...")
if gotool.BcryptUtils.RsaVerySignWithSha256([]byte(data), signData, pubKey) {
fmt.Println("The signature information is verified successfully. Confirm that it is the correct private key signature!!")
}

fmt.Println("-------------------------------Perform encryption and decryption operations-----------------------------------------")
ciphertext := gotool.BcryptUtils.RsaEncrypt([]byte(data), pubKey)
fmt.Println("Data encrypted by public key:", hex.EncodeToString(ciphertext))
sourceData := gotool.BcryptUtils.RsaDecrypt(ciphertext, prvKey)
fmt.Println("Data decrypted by private key:", string(sourceData))
}
//out
== = RUN   TestRsa
-------------------------------obtain RSA Public private key-----------------------------------------
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCgHh1ZYFjlxrIJYjjWGFaLwC8Oov8KqyMtHa+GauF121dperr3
i46JyDoskoSBhbkmqv70LMNrjqVdttdIsC0BtH9ThWLBwKVLH56EqfzqlzClKZEh
WTNaddCSuxoZpN33mwS82DCjZe3d7nAPdEGD5pSBx6TVt5bG1c3NVAmcBQIDAQAB
AoGAWc5KO9T0R3xYYzb6Fer0r9GNEzKMxdkTE7zws/3Cky4BKyIxN6LIwbLSHinX
tCXioTOLaDyrJuqNCbEBsr1NoCIPxnswA5Jm5QDYO5x9aq4u8+SZ9KqLbMrO1JDS
ZV7Cbiblz1xNMfdVIvlVjD5RdEotbYTbHI2CZUoPsjHng8kCQQDHi6TJYJqvej8r
q46ZceuWHDgE81Wu16RrA/kZKi6MJAApQtfO/4HM6W/ImbCjZ2rSYxqnAlIg/GxA
dT6iJABjAkEAzWra06RyhGm3lk9j9Xxc0YPX6VX7qT5Iq6c7ry1JtTSeVOksKANG
elaNnCj8YYUgj7BeBBcMMvLd39hP1h06dwJAINTyHQwfB2ZGxImqocajq4QjF3Vu
EKF8dPsnXiOZmwdFW4Sa+30Av1VdRhU7gfc/FTSnKvlvx+ugaA6iao0f3wJBALa8
sTCH4WwUE8K+m4DeAkBMVn34BKnZg5JYcgrzcdemmJeW2rY5u6/HYbCi8WnboUzS
K8Dds/d7AJBKgTNLyx8CQBAeU0St3Vk6SJ6H71J8YtVxlRGDjS2fE0JfUBrpI/bg
r/QI8yMAMyFkt1YshN+UNWJcvR5SXQnyT/udnWJIdg4 =
-----END RSA PRIVATE KEY-----

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgHh1ZYFjlxrIJYjjWGFaLwC8O
ov8KqyMtHa+GauF121dperr3i46JyDoskoSBhbkmqv70LMNrjqVdttdIsC0BtH9T
hWLBwKVLH56EqfzqlzClKZEhWTNaddCSuxoZpN33mwS82DCjZe3d7nAPdEGD5pSB
x6TVt5bG1c3NVAmcBQIDAQAB
-----END PUBLIC KEY-----

-------------------------------Perform signature and verification operations-----------------------------------------
Sign the message...
Signature information of message: 1 fcf20c4fb548c8fc0906e369287feb84c861bf488d822d78a0eada23d1af66ed3a12e9440d7181b1748fd0ad805222cf2ce7ce1f6772b330ef11b717700ba26945dda9d749a5c4d8c108ede103c17bed92801a4c3fbc1ebf38d10bf4bf183713eeb7f429acc3dcc3812366a324737f756720f3f9e75ddda1e024a7698b89163

Verify signature information...
The signature information is verified successfully. Confirm that it is the correct private key signature!!
-------------------------------Perform encryption and decryption operations-----------------------------------------
Data encrypted by public key: 637 b05798c1cf95cfcc63adf228645c77f8e9a9f34b12b722e6938ded8c9560a0430171a4f940d3fb2d96bc6c470c80a817d81f4a2669b991adbff5b22b335129e514c921083ce3e64c1c876409d9b763d5e8e269797283ef951a364da6a59a1d8454391356cb0cd0808092e9dd7ac371f9247a43760f3c82b7ad26a32a7a807
 Private key decrypted data: I am encrypted data. Remember me-------------------------------
--- PASS: TestRsa (0.02s)
PASS

Logs log printing tool

gotool.Logs.ErrorLog exception log

gotool.Logs.InfoLog load log

gotool.Logs.DebugLog debug log

func TestLogs(t *testing.T) {
	gotool.Logs.ErrorLog().Println("Error Log test")
	gotool.Logs.InfoLog().Println("Info Log test")
	gotool.Logs.DebugLog().Println("Debug Log test")
}
//out
=== RUN   TestLogs
[ERROR] 2021/07/07 15:58:10 logs_test.go:9: Error Log test
[INFO] 2021/07/07 15:58:10 logs_test.go:10: Info Log test
[DEBUG] 2021/07/07 15:58:10 logs_test.go:11: Debug Log test
--- PASS: TestLogs (0.00s)
PASS

PageUtils paging tool

gotool.PageUtils.Paginator rainbow Pagination

func TestPage(t *testing.T) {
	paginator := gotool.PageUtils.Paginator(5, 20, 500)
	fmt.Println(paginator)
}
//out
=== RUN   TestPage
map[AfterPage:6 beforePage:4 currPage:5 pages:[3 4 5 6 7] totalPages:25]
--- PASS: TestPage (0.00s)
PASS
//Description AfterPage next page beforePage previous page currPage current page pages page totalPages total pages

HttpUtils

A simple "HTTP request" package of golang GET POST DELETE PUT

How do we use HttpUtils?

resp, err := gotool.HttpUtils.Get("http://127.0.0.1:8000")
resp, err := gotool.HttpUtils.SetTimeout(5).Get("http://127.0.0.1:8000")
resp, err := gotool.HttpUtils.Debug(true).SetHeaders(map[string]string{}).Get("http://127.0.0.1:8000")

OR

req := gotool.HttpUtils.NewRequest()
req := gotool.HttpUtils.NewRequest().Debug(true).SetTimeout(5)
resp, err := req.Get("http://127.0.0.1:8000")
resp, err := req.Get("http://127.0.0.1:8000",nil)
resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest")
resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest", "address=beijing")

Set request header

req.SetHeaders(map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Connection": "keep-alive",
})

req.SetHeaders(map[string]string{
"Source":"api",
})

Set Cookies

req.SetCookies(map[string]string{
"name":"json",
"token":"",
})

OR

gotool.HttpUtils.SetCookies(map[string]string{
"age":"19",
}).Post()

Set timeout

req.SetTimeout(5) //default 30s

Object oriented operation mode

req := gotool.HttpUtils.NewRequest().
Debug(true).
SetHeaders(map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
}).SetTimeout(5)
resp, err := req.Get("http://127.0.0.1")

resp,err := gotool.HttpUtils.NewRequest().Get("http://127.0.0.1")

GET

Query parameters

resp, err := req.Get("http://127.0.0.1:8000")
resp, err := req.Get("http://127.0.0.1:8000",nil)
resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest")
resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest", "address=beijing")

OR

resp, err := gotool.HttpUtils.Get("http://127.0.0.1:8000")
resp, err := gotool.HttpUtils.Debug(true).SetHeaders(map[string]string{}).Get("http://127.0.0.1:8000")

Multi parameter

resp, err := req.Get("http://127.0.0.1:8000?id=10&title=HttpRequest", map[string]interface{}{
"name":  "jason",
"score": 100,
})
defer resp.Close()

body, err := resp.Body()
if err != nil {
return
}

return string(body)

POST

// Send nil
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000")

// Send integer
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", 100)

// Send []byte
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", []byte("bytes data"))

// Send io.Reader
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", bytes.NewReader(buf []byte))
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", strings.NewReader("string data"))
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", bytes.NewBuffer(buf []byte))

// Send string
resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000", "title=github&type=1")

// Send JSON
resp, err := gotool.HttpUtils.JSON().Post("http://127.0.0.1:8000", "{\"id\":10,\"title\":\"HttpRequest\"}")

// Send map[string]interface{}{}
resp, err := req.Post("http://127.0.0.1:8000", map[string]interface{}{
"id":    10,
"title": "HttpRequest",
})
defer resp.Close()

body, err := resp.Body()
if err != nil {
return
}
return string(body)

resp, err := gotool.HttpUtils.Post("http://127.0.0.1:8000")
resp, err := gotool.HttpUtils.JSON().Post("http://127.0.0.1:8000", map[string]interface{}{"title":"github"})
resp, err := gotool.HttpUtils.Debug(true).SetHeaders(map[string]string{}).JSON().Post("http://127.0.0.1:8000","{\"title\":\"github\"}")

proxy pattern

proxy, err := url.Parse("http://proxyip:proxyport")
if err != nil {
log.Println(err)
}

resp, err := gotool.HttpUtils.Proxy(http.ProxyURL(proxy)).Get("http://127.0.0.1:8000/ip")
defer resp.Close()

if err != nil {
log.Println("Request error: %v", err.Error())
}

body, err := resp.Body()
if err != nil {
log.Println("Get body error: %v", err.Error())
}
log.Println(string(body))

Upload file

Params: url, filename, fileinput

resp, err := req.Upload("http://127.0.0.1:8000/upload", "/root/demo.txt", "uploadFile")
body, err := resp.Body()
defer resp.Close()
if err != nil {
return
}
return string(body)

Prompt mode

Default false

req.Debug(true)

Print as standard output:

[HttpRequest]
-------------------------------------------------------------------
Request: GET http: //127.0.0.1:8000?name=iceview&age=19&score=100
Headers: map[Content-Type:application/x-www-form-urlencoded]
Cookies: map[]
Timeout: 30s
ReqBody: map[age:19 score:100]
-------------------------------------------------------------------

Json

Post JSON request

Set request header

 req.SetHeaders(map[string]string{"Content-Type": "application/json"})

Or

req.JSON().Post("http://127.0.0.1:8000", map[string]interface{}{
"id":    10,
"title": "github",
})

req.JSON().Post("http://127.0.0.1:8000", "{\"title\":\"github\",\"id\":10}")

Post request

resp, err := req.Post("http://127.0.0.1:8000", map[string]interface{}{
"id":    10,
"title": "HttpRequest",
})

Print formatted JSON

str, err := resp.Export()
if err != nil {
return
}

Ungroup JSON

var u User
err := resp.Json(&u)
if err != nil {
return err
}

var m map[string]interface{}
err := resp.Json(&m)
if err != nil {
return err
}

Topics: Go