gotool是一個小而全的Golang工具集,主要是將日常開發中常用的到方法進行提煉整合,避免重複造輪子,提高工作效率,每一個方法都是作者經過工作經驗,和從以往的專案中提煉出來的。
如何使用gotool呢?
安裝
go get github.com/druidcaesa/gotool
go.mod github.com/druidcaesa/gotool
引入
import "github.com/druidcaesa/gotool"
golang一個string常用工具集,基本涵蓋了開發中經常用到的工具,目前正在不端的完善中
gotool.StrUtils.ReplacePlaceholder 佔位符替換
func TestStringReplacePlaceholder(t *testing.T) {
s := "你是我的{},我是你的{}"
placeholder, err := gotool.StrUtils.ReplacePlaceholder(s, "唯一", "所有")
if err == nil {
fmt.Println(placeholder)
}
}
//out
=== RUN TestStringReplacePlaceholder
你是我的唯一,我是你的所有
--- PASS: TestStringReplacePlaceholder (0.00s)
PASS
gotool.StrUtils.RemoveSuffix 去除副檔名獲取檔名
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 獲取副檔名
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 判斷字串是否未空,我空返回ture
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
golang一個時間操作工具集,基本涵蓋了開發中經常用到的工具,目前正在不端的完善中
gotool.DateUtil.FormatToString 時間格式化成字串
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 可進行任意組合 比如 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 判斷時間是否為空
//時間為空 true 否則 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 獲取當前時間 等同於time.Now(),為了統一化所以將此方法也納入到工具中
gotool.DateUtil.InterpretStringToTimestamp 字串格式化成時間型別
//引數一 需要格式化的時間字串 引數二 字串格式,需要和需格式化字串格式一致
//如 2021-6-4 對應YYYY-MM-DD 2021.6.4 對應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 時間戳轉時間
func TestUnixToTime(t *testing.T) {
unix := gotool.DateUtil.Now().Unix()
fmt.Println("時間戳----------------------->", unix)
toTime := gotool.DateUtil.UnixToTime(unix)
fmt.Println(toTime)
}
//out
=== RUN TestUnixToTime
時間戳-----------------------> 1625645682
2021-07-07 16:14:42 +0800 CST
--- PASS: TestUnixToTime (0.00s)
PASS
gotool.DateUtil.GetWeekDay 獲取星期幾
func TestGetWeekDay(t *testing.T) {
now := gotool.DateUtil.Now()
day := gotool.DateUtil.GetWeekDay(now)
fmt.Println("今天是-----------------周", day)
}
//out
=== RUN TestGetWeekDay
今天是-----------------周 3
--- PASS: TestGetWeekDay (0.00s)
PASS
gotool.DateUtil.MinuteAddOrSub,HourAddOrSub,DayAddOrSub 時間計算工具
//時間計算
func TestTimeAddOrSub(t *testing.T) {
now := gotool.DateUtil.Now()
fmt.Println("現在時間是--------------------->", now)
sub := gotool.DateUtil.MinuteAddOrSub(now, 10)
fmt.Println("分鐘計算結果-------------------->", sub)
sub = gotool.DateUtil.MinuteAddOrSub(now, -10)
fmt.Println("分鐘計算結果-------------------->", sub)
sub = gotool.DateUtil.HourAddOrSub(now, 10)
fmt.Println("小時計算結果-------------------->", sub)
sub = gotool.DateUtil.HourAddOrSub(now, -10)
fmt.Println("小時計算結果-------------------->", sub)
sub = gotool.DateUtil.DayAddOrSub(now, 10)
fmt.Println("天計算結果-------------------->", sub)
sub = gotool.DateUtil.DayAddOrSub(now, -10)
fmt.Println("天計算結果-------------------->", sub)
}
//現在時間是---------------------> 2021-07-07 11:18:17.8295757 +0800 CST m=+0.012278001
//分鐘計算結果--------------------> 2021-07-07 11:28:17.8295757 +0800 CST m=+600.012278001
//分鐘計算結果--------------------> 2021-07-07 11:08:17.8295757 +0800 CST m=-599.987721999
//小時計算結果--------------------> 2021-07-07 21:18:17.8295757 +0800 CST m=+36000.012278001
//小時計算結果--------------------> 2021-07-07 01:18:17.8295757 +0800 CST m=-35999.987721999
//天計算結果--------------------> 2021-07-17 11:18:17.8295757 +0800 CST m=+864000.012278001
//天計算結果--------------------> 2021-06-27 11:18:17.8295757 +0800 CST m=-863999.987721999
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)獲取公曆某月天數 2021年7月天數
gotool.ConvertUtils.IsLeapYear(2021)獲取某年是否是瑞年 true是 false不是
gotool.ConvertUtils.GetLeapMonth(2021)獲取某年閏月月份
gotool.BcryptUtils.Generate 加密處理,多用於密碼進行加密後資料庫儲存使用,不可逆
gotool.BcryptUtils.CompareHash 加密後和未加密密碼對比,多用於登入驗證使用
func TestGenerate(t *testing.T) {
//進行加密
generate := gotool.BcryptUtils.Generate("123456789")
fmt.Println(generate)
//進行加密對比
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加密
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(獲取公鑰和私鑰),
RsaSignWithSha256(進行簽名),
RsaVerySignWithSha256(驗證),
RsaEncrypt(公鑰加密),
RsaDecrypt(私鑰解密)
func TestRsa(t *testing.T) {
//rsa 金鑰檔案產生
fmt.Println("-------------------------------獲取RSA公私鑰-----------------------------------------")
prvKey, pubKey := gotool.BcryptUtils.GenRsaKey()
fmt.Println(string(prvKey))
fmt.Println(string(pubKey))
fmt.Println("-------------------------------進行簽名與驗證操作-----------------------------------------")
var data = "我是被加密的資料記住我哦-------------------------------"
fmt.Println("對訊息進行簽名操作...")
signData := gotool.BcryptUtils.RsaSignWithSha256([]byte(data), prvKey)
fmt.Println("訊息的簽名資訊: ", hex.EncodeToString(signData))
fmt.Println("\n對簽名資訊進行驗證...")
if gotool.BcryptUtils.RsaVerySignWithSha256([]byte(data), signData, pubKey) {
fmt.Println("簽名資訊驗證成功,確定是正確私鑰簽名!!")
}
fmt.Println("-------------------------------進行加密解密操作-----------------------------------------")
ciphertext := gotool.BcryptUtils.RsaEncrypt([]byte(data), pubKey)
fmt.Println("公鑰加密後的資料:", hex.EncodeToString(ciphertext))
sourceData := gotool.BcryptUtils.RsaDecrypt(ciphertext, prvKey)
fmt.Println("私鑰解密後的資料:", string(sourceData))
}
//out
== = RUN TestRsa
-------------------------------獲取RSA公私鑰-----------------------------------------
-----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-----
-------------------------------進行簽名與驗證操作-----------------------------------------
對訊息進行簽名操作...
訊息的簽名資訊: 1fcf20c4fb548c8fc0906e369287feb84c861bf488d822d78a0eada23d1af66ed3a12e9440d7181b1748fd0ad805222cf2ce7ce1f6772b330ef11b717700ba26945dda9d749a5c4d8c108ede103c17bed92801a4c3fbc1ebf38d10bf4bf183713eeb7f429acc3dcc3812366a324737f756720f3f9e75ddda1e024a7698b89163
對簽名資訊進行驗證...
簽名資訊驗證成功,確定是正確私鑰簽名!!
-------------------------------進行加密解密操作-----------------------------------------
公鑰加密後的資料: 637b05798c1cf95cfcc63adf228645c77f8e9a9f34b12b722e6938ded8c9560a0430171a4f940d3fb2d96bc6c470c80a817d81f4a2669b991adbff5b22b335129e514c921083ce3e64c1c876409d9b763d5e8e269797283ef951a364da6a59a1d8454391356cb0cd0808092e9dd7ac371f9247a43760f3c82b7ad26a32a7a807
私鑰解密後的資料: 我是被加密的資料記住我哦-------------------------------
--- PASS: TestRsa (0.02s)
PASS
gotool.Logs.ErrorLog 異常日誌
gotool.Logs.InfoLog 載入日誌
gotool.Logs.DebugLog 除錯日誌
func TestLogs(t *testing.T) {
gotool.Logs.ErrorLog().Println("Error日誌測試")
gotool.Logs.InfoLog().Println("Info日誌測試")
gotool.Logs.DebugLog().Println("Debug日誌測試")
}
//out
=== RUN TestLogs
[ERROR] 2021/07/07 15:58:10 logs_test.go:9: Error日誌測試
[INFO] 2021/07/07 15:58:10 logs_test.go:10: Info日誌測試
[DEBUG] 2021/07/07 15:58:10 logs_test.go:11: Debug日誌測試
--- PASS: TestLogs (0.00s)
PASS
gotool.PageUtils.Paginator 彩虹分頁
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
//說明 AfterPage 下一頁 beforePage前一頁 currPage當前頁 pages頁碼 totalPages總頁數
golang 的一個簡單的“HTTP 請求”包 GET
POST
DELETE
PUT
我們如何使用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")
設定請求頭
req.SetHeaders(map[string]string{
"Content-Type": "application/x-www-form-urlencoded",
"Connection": "keep-alive",
})
req.SetHeaders(map[string]string{
"Source":"api",
})
設定Cookies
req.SetCookies(map[string]string{
"name":"json",
"token":"",
})
OR
gotool.HttpUtils.SetCookies(map[string]string{
"age":"19",
}).Post()
設定超時時間
req.SetTimeout(5) //default 30s
物件導向的操作模式
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
查詢引數
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")
多引數
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, 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))
上傳檔案
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)
提示模式
預設 false
req.Debug(true)
以標準輸出列印:
[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 請求
設定請求頭
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 請求
resp, err := req.Post("http://127.0.0.1:8000", map[string]interface{}{
"id": 10,
"title": "HttpRequest",
})
列印格式化的 JSON
str, err := resp.Export()
if err != nil {
return
}
解組 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
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結