Skip to content

Commit

Permalink
utils:对工具类进行分组改造
Browse files Browse the repository at this point in the history
  • Loading branch information
keepchen committed Feb 11, 2025
1 parent 773b127 commit f6bf318
Show file tree
Hide file tree
Showing 86 changed files with 4,104 additions and 304 deletions.
8 changes: 4 additions & 4 deletions examples/pkg/app/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,14 +95,14 @@ func StartServer(wg *sync.WaitGroup) {
fmt.Println("call user function [after] to do something...")
job0 := "print now datetime"
cancel0 := schedule.NewJob(job0, func() {
fmt.Println("now: ", utils.FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN))
fmt.Println("now: ", utils.Datetime().FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN))
}).RunAt(schedule.EveryMinute)
time.AfterFunc(time.Minute*3, cancel0)

job1 := "print hello"
cancel1 := schedule.NewJob(job1, func() {
time.Sleep(time.Second * 10)
fmt.Println(utils.FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN), "hello")
fmt.Println(utils.Datetime().FormatDate(time.Now(), utils.YYYY_MM_DD_HH_MM_SS_EN), "hello")
sail.GetLogger().Info("print log info to console",
zap.String("value", "go-sail"),
zap.Errors("errors", []error{nil}))
Expand Down Expand Up @@ -141,7 +141,7 @@ func RegisterServicesToNacos(wg *sync.WaitGroup) {

nc := nacos.GetNamingClient()
var param vo.RegisterInstanceParam
localIp, err := utils.GetLocalIP()
localIp, err := utils.IP().GetLocal()
if err == nil {
param.Ip = localIp
}
Expand All @@ -168,7 +168,7 @@ func RegisterServicesToNacos(wg *sync.WaitGroup) {
func UnregisterServiceFromNacos() {
nc := nacos.GetNamingClient()
var param vo.DeregisterInstanceParam
localIp, err := utils.GetLocalIP()
localIp, err := utils.IP().GetLocal()
if err == nil {
param.Ip = localIp
}
Expand Down
2 changes: 1 addition & 1 deletion sail/config/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func PrintTemplateConfig(format string, writeToFile ...string) {
}

if len(writeToFile) > 0 {
err := utils.FilePutContents(cfgStr, writeToFile[0])
err := utils.File().PutContents(cfgStr, writeToFile[0])
if err != nil {
fmt.Printf("[GO-SAIL] <Config> dump config to file {%s} error: %s\n", writeToFile[0], err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion sail/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func printSummaryInfo(conf config.HttpServerConf, ginEngine *gin.Engine) {
var (
protocol = "http:"
messages bytes.Buffer
localIp, _ = utils.GetLocalIP()
localIp, _ = utils.IP().GetLocal()
delimiter = []byte(strings.Repeat("=", 88))
subDelimiter = []byte(strings.Repeat("-", 88))
repoLink = "Repository: https://github.com/keepchen/go-sail"
Expand Down
4 changes: 2 additions & 2 deletions schedule/delay.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ func (j *taskJob) RunAfter(delay time.Duration) (cancel CancelFunc) {
j.task()
return
}
if utils.RedisTryLock(j.lockerKey) {
if utils.RedisLocker().TryLock(j.lockerKey) {
defer func() {
utils.RedisUnlock(j.lockerKey)
utils.RedisLocker().Unlock(j.lockerKey)
j.lockedByMe = false
}()
j.lockedByMe = true
Expand Down
6 changes: 3 additions & 3 deletions schedule/interval.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@ func (j *taskJob) run() {
j.task()
return
}
if utils.RedisTryLock(j.lockerKey) {
if utils.RedisLocker().TryLock(j.lockerKey) {
defer func() {
utils.RedisUnlock(j.lockerKey)
utils.RedisLocker().Unlock(j.lockerKey)
j.lockedByMe = false
}()
j.lockedByMe = true
Expand All @@ -51,7 +51,7 @@ func (j *taskJob) run() {
//收到退出信号,终止任务
case <-j.cancelTaskChan:
if j.withoutOverlapping && j.lockedByMe {
utils.RedisUnlock(j.lockerKey)
utils.RedisLocker().Unlock(j.lockerKey)
}

taskSchedules.mux.Lock()
Expand Down
4 changes: 2 additions & 2 deletions schedule/specs.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ func (j *taskJob) RunAt(crontabExpr string) (cancel CancelFunc) {
j.task()
return
}
if utils.RedisTryLock(j.lockerKey) {
if utils.RedisLocker().TryLock(j.lockerKey) {
defer func() {
utils.RedisUnlock(j.lockerKey)
utils.RedisLocker().Unlock(j.lockerKey)
j.lockedByMe = false
}()
j.lockedByMe = true
Expand Down
35 changes: 29 additions & 6 deletions utils/aes.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,38 @@ import (
"io"
)

// KEY 密钥
const KEY = "fakeKeyChangeMe!"
type aesImpl struct {
}

// IAes aes接口
type IAes interface {
// Encode aes加密
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
Encode(rawString, key string) (string, error)
// Decode aes解密
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
Decode(encryptedString, key string) (string, error)
}

// Aes 实例化aes工具类
func Aes() IAes {
return &aesImpl{}
}

var _ IAes = aesImpl{}

// AesEncode aes加密
// Encode aes加密
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
func AesEncode(rawString, key string) (string, error) {
func (aesImpl) Encode(rawString, key string) (string, error) {
plainText := []byte(rawString)

block, err := aes.NewCipher([]byte(key))
Expand All @@ -38,12 +61,12 @@ func AesEncode(rawString, key string) (string, error) {

}

// AesDecode aes解密
// Decode aes解密
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
func AesDecode(encryptedString, key string) (string, error) {
func (aesImpl) Decode(encryptedString, key string) (string, error) {
cipherText, err := base64.StdEncoding.DecodeString(encryptedString)
if err != nil {
return "", err
Expand Down
73 changes: 73 additions & 0 deletions utils/aes_deprecated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package utils

import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"io"
)

// AesEncode aes加密
//
// Deprecated: AesEncode is deprecated,it will be removed in the future.
//
// Please use Aes().Encode() instead.
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
func AesEncode(rawString, key string) (string, error) {
plainText := []byte(rawString)

block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", err
}

cipherText := make([]byte, aes.BlockSize+len(plainText))
iv := cipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return "", err
}

stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(cipherText[aes.BlockSize:], plainText)

return base64.StdEncoding.EncodeToString(cipherText), nil

}

// AesDecode aes解密
//
// Deprecated: AesDecode is deprecated,it will be removed in the future.
//
// Please use Aes().Decode() instead.
//
// 使用CFB
//
// key应该是一个16或24或32位长度的字符
func AesDecode(encryptedString, key string) (string, error) {
cipherText, err := base64.StdEncoding.DecodeString(encryptedString)
if err != nil {
return "", err
}

block, err := aes.NewCipher([]byte(key))
if err != nil {
return "", nil
}

if len(cipherText) < aes.BlockSize {
return "", errors.New("CipherText block size is too short")
}

iv := cipherText[:aes.BlockSize]
cipherText = cipherText[aes.BlockSize:]

stream := cipher.NewCFBDecrypter(block, iv)
stream.XORKeyStream(cipherText, cipherText)

return string(cipherText), nil
}
28 changes: 28 additions & 0 deletions utils/aes_deprecated_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

var rawStringDeprecated = "hello world!"

// KeyForTestDeprecated 测试密钥
const KeyForTestDeprecated = "fakeKeyChangeMe!"

func TestAesEncode(t *testing.T) {
encodedString, err := AesEncode(rawStringDeprecated, KeyForTestDeprecated)
t.Log(encodedString)
assert.NoError(t, err)
}

func TestAesDecode(t *testing.T) {
encodedString, err := AesEncode(rawStringDeprecated, KeyForTestDeprecated)
t.Log(encodedString)
assert.NoError(t, err)
decodedString, err := AesDecode(encodedString, KeyForTestDeprecated)
t.Log(decodedString)
assert.NoError(t, err)
assert.Equal(t, decodedString, rawStringDeprecated)
}
13 changes: 8 additions & 5 deletions utils/aes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,20 @@ import (

var rawString = "hello world!"

func TestAesEncode(t *testing.T) {
encodedString, err := AesEncode(rawString, KEY)
// KeyForTest 测试密钥
const KeyForTest = "fakeKeyChangeMe!"

func TestAesImplEncode(t *testing.T) {
encodedString, err := Aes().Encode(rawString, KeyForTest)
t.Log(encodedString)
assert.NoError(t, err)
}

func TestAesDecode(t *testing.T) {
encodedString, err := AesEncode(rawString, KEY)
func TestAesImplDecode(t *testing.T) {
encodedString, err := Aes().Encode(rawString, KeyForTest)
t.Log(encodedString)
assert.NoError(t, err)
decodedString, err := AesDecode(encodedString, KEY)
decodedString, err := Aes().Decode(encodedString, KeyForTest)
t.Log(decodedString)
assert.NoError(t, err)
assert.Equal(t, decodedString, rawString)
Expand Down
26 changes: 22 additions & 4 deletions utils/base64.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,30 @@ package utils

import "encoding/base64"

//Base64Encode base64编码
func Base64Encode(rawBytes []byte) string {
type base64Impl struct {
}

// IBase64 base64接口
type IBase64 interface {
// Encode base64编码
Encode(rawBytes []byte) string
// Decode base64解码
Decode(encodedString string) ([]byte, error)
}

// Base64 实例化base64工具类
func Base64() IBase64 {
return &base64Impl{}
}

var _ IBase64 = base64Impl{}

// Encode base64编码
func (base64Impl) Encode(rawBytes []byte) string {
return base64.StdEncoding.EncodeToString(rawBytes)
}

//Base64Decode base64解码
func Base64Decode(encodedString string) ([]byte, error) {
// Decode base64解码
func (base64Impl) Decode(encodedString string) ([]byte, error) {
return base64.StdEncoding.DecodeString(encodedString)
}
21 changes: 21 additions & 0 deletions utils/base64_deprecated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package utils

import "encoding/base64"

// Base64Encode base64编码
//
// Deprecated: Base64Encode is deprecated,it will be removed in the future.
//
// Please use Base64().Encode() instead.
func Base64Encode(rawBytes []byte) string {
return base64.StdEncoding.EncodeToString(rawBytes)
}

// Base64Decode base64解码
//
// Deprecated: Base64Decode is deprecated,it will be removed in the future.
//
// Please use Base64().Decode() instead.
func Base64Decode(encodedString string) ([]byte, error) {
return base64.StdEncoding.DecodeString(encodedString)
}
22 changes: 22 additions & 0 deletions utils/base64_deprecated_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestBase64Encode(t *testing.T) {
encodedString := Base64Encode([]byte(rawString))
t.Log(encodedString)
assert.Equal(t, "aGVsbG8gd29ybGQh", encodedString)
}

func TestBase64Decode(t *testing.T) {
encodedString := Base64Encode([]byte(rawString))

decodeBytes, err := Base64Decode(encodedString)
t.Log(rawString, encodedString, string(decodeBytes))
assert.NoError(t, err)
assert.Equal(t, string(decodeBytes), rawString)
}
10 changes: 5 additions & 5 deletions utils/base64_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,16 @@ import (
"github.com/stretchr/testify/assert"
)

func TestBase64Encode(t *testing.T) {
encodedString := Base64Encode([]byte(rawString))
func TestBase64ImplEncode(t *testing.T) {
encodedString := Base64().Encode([]byte(rawString))
t.Log(encodedString)
assert.Equal(t, "aGVsbG8gd29ybGQh", encodedString)
}

func TestBase64Decode(t *testing.T) {
encodedString := Base64Encode([]byte(rawString))
func TestBase64ImplDecode(t *testing.T) {
encodedString := Base64().Encode([]byte(rawString))

decodeBytes, err := Base64Decode(encodedString)
decodeBytes, err := Base64().Decode(encodedString)
t.Log(rawString, encodedString, string(decodeBytes))
assert.NoError(t, err)
assert.Equal(t, string(decodeBytes), rawString)
Expand Down
Loading

0 comments on commit f6bf318

Please sign in to comment.