add comments, code refactor, fix typo

This commit is contained in:
MaysWind
2020-12-23 00:09:35 +08:00
parent bb10498893
commit 17d1cd8719
10 changed files with 49 additions and 13 deletions
+2
View File
@@ -11,6 +11,7 @@ import (
"github.com/mayswind/lab/pkg/errs"
)
// PrintSuccessResult writes success response to current http context
func PrintSuccessResult(c *core.Context, result interface{}) {
c.JSON(http.StatusOK, gin.H{
"success": true,
@@ -18,6 +19,7 @@ func PrintSuccessResult(c *core.Context, result interface{}) {
})
}
// PrintErrorResult writes error response to current http context
func PrintErrorResult(c *core.Context, err *errs.Error) {
c.SetResponseError(err)
+8
View File
@@ -2,14 +2,18 @@ package utils
import "strconv"
// Int32ToString returns the textual representation of this number
func Int32ToString(num int) string {
return strconv.Itoa(num)
}
// StringToInt32 parses a textual representation of the number to int32
func StringToInt32(str string) (int, error) {
return strconv.Atoi(str)
}
// StringTryToInt32 parses a textual representation of the number to int32 if str is valid,
// or returns the default value
func StringTryToInt32(str string, defaultValue int) int {
num, err := StringToInt32(str)
@@ -20,14 +24,18 @@ func StringTryToInt32(str string, defaultValue int) int {
return num
}
// Int64ToString returns the textual representation of this number
func Int64ToString(num int64) string {
return strconv.FormatInt(num, 10)
}
// StringToInt64 parses a textual representation of the number to int64
func StringToInt64(str string) (int64, error) {
return strconv.ParseInt(str, 10, 64)
}
// StringTryToInt64 parses a textual representation of the number to int64 if str is valid,
// or returns the default value
func StringTryToInt64(str string, defaultValue int64) int64 {
num, err := StringToInt64(str)
+10 -3
View File
@@ -2,24 +2,31 @@ package utils
import "time"
const LongDateTimeFormat = "2006-01-02 15:04:05"
const (
longDateTimeFormat = "2006-01-02 15:04:05"
)
// FormatToLongDateTime returns a textual representation of the time value formatted by long date time format
func FormatToLongDateTime(t time.Time) string {
return t.Format(LongDateTimeFormat)
return t.Format(longDateTimeFormat)
}
// ParseFromLongDateTime parses a formatted string in long date time format
func ParseFromLongDateTime(t string) (time.Time, error) {
return time.Parse(LongDateTimeFormat, t)
return time.Parse(longDateTimeFormat, t)
}
// GetMinTransactionTimeFromUnixTime returns the minimum transaction time from unix time
func GetMinTransactionTimeFromUnixTime(unixTime int64) int64 {
return unixTime * 1000
}
// GetMaxTransactionTimeFromUnixTime returns the maximum transaction time from unix time
func GetMaxTransactionTimeFromUnixTime(unixTime int64) int64 {
return unixTime*1000 + 999
}
// GetUnixTimeFromTransactionTime returns unix time from the transaction time
func GetUnixTimeFromTransactionTime(transactionTime int64) int64 {
return transactionTime / 1000
}
+2
View File
@@ -7,6 +7,7 @@ import (
"github.com/mayswind/lab/pkg/errs"
)
// GetLocalIPAddressesString returns all local ip address, every ip split by comma
func GetLocalIPAddressesString() (string, error) {
localAddrs, err := GetLocalIPAddresses()
@@ -31,6 +32,7 @@ func GetLocalIPAddressesString() (string, error) {
return string(buff.Bytes()), nil
}
// GetLocalIPAddresses returns all local ip address object array
func GetLocalIPAddresses() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs()
+1
View File
@@ -5,6 +5,7 @@ import (
"math/big"
)
// GetRandomInteger returns a random number, the max parameter represents upper limit
func GetRandomInteger(max int) (int, error) {
result, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
+1
View File
@@ -5,6 +5,7 @@ import (
"encoding/gob"
)
// Clone deep-clones src object to dst object
func Clone(src, dst interface{}) error {
var buf bytes.Buffer
+9 -6
View File
@@ -3,19 +3,22 @@ package utils
import "regexp"
var (
UsernamePattern = regexp.MustCompile("^(?i)[a-z0-9_-]+$")
EmailPattern = regexp.MustCompile("^(?i)(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$")
HexRGBColorPattern = regexp.MustCompile("^(?i)([0-9a-f]{6}|[0-9a-f]{3})$")
usernamePattern = regexp.MustCompile("^(?i)[a-z0-9_-]+$")
emailPattern = regexp.MustCompile("^(?i)(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$")
hexRGBColorPattern = regexp.MustCompile("^(?i)([0-9a-f]{6}|[0-9a-f]{3})$")
)
// IsValidUsername reports whether username is valid
func IsValidUsername(username string) bool {
return UsernamePattern.MatchString(username)
return usernamePattern.MatchString(username)
}
// IsValidEmail reports whether email is valid
func IsValidEmail(email string) bool {
return EmailPattern.MatchString(email)
return emailPattern.MatchString(email)
}
// IsValidHexRGBColor reports whether color is valid
func IsValidHexRGBColor(color string) bool {
return HexRGBColorPattern.MatchString(color)
return hexRGBColorPattern.MatchString(color)
}
+2
View File
@@ -1,5 +1,6 @@
package utils
// Int64SliceMinus returns a int64 array which contains items in s1 but not in s2
func Int64SliceMinus(s1, s2 []int64) []int64 {
if s1 == nil {
return nil
@@ -21,6 +22,7 @@ func Int64SliceMinus(s1, s2 []int64) []int64 {
return ret
}
// ToUniqueInt64Slice returns a int64 array which does not have duplicated items
func ToUniqueInt64Slice(items []int64) []int64 {
uniqueItems := make([]int64, 0, len(items))
itemExistMap := make(map[int64]bool)
+13 -3
View File
@@ -22,6 +22,7 @@ const (
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS)
)
// SubString returns part of the source string according to start index and length
func SubString(str string, start int, length int) string {
chars := []rune(str)
realLength := len(chars)
@@ -55,6 +56,7 @@ func SubString(str string, start int, length int) string {
return string(chars[start:end])
}
// GetFirstLowerCharString returns the source string parameter, but makes the first character lower case
func GetFirstLowerCharString(s string) string {
if s == "" {
return s
@@ -70,6 +72,7 @@ func GetFirstLowerCharString(s string) string {
return string(chars)
}
// GetRandomString returns a random string of which length is n
func GetRandomString(n int) (string, error) {
var result = make([]byte, n)
@@ -86,6 +89,7 @@ func GetRandomString(n int) (string, error) {
return string(result), nil
}
// GetRandomNumberOrLetter returns a random string which only contains number or letter characters
func GetRandomNumberOrLetter(n int) (string, error) {
var result = make([]byte, n)
@@ -102,12 +106,14 @@ func GetRandomNumberOrLetter(n int) (string, error) {
return string(result), nil
}
// MD5Encode returns a hashed string by md5
func MD5Encode(data []byte) []byte {
m := md5.New()
m.Write(data)
return m.Sum(nil)
}
// AESGCMEncrypt returns a encrypted string by aes-gcm
func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
@@ -133,6 +139,7 @@ func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
return result, nil
}
// AESGCMEncrypt returns a decrypted string by aes-gcm
func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
@@ -164,21 +171,24 @@ func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
return plainText, nil
}
// EncodePassword returns a encoded password
func EncodePassword(password string, salt string) string {
encodedPassword := pbkdf2.Key([]byte(password), []byte(salt), 10000, 48, sha256.New) // 256^48 = 64^64
return strings.TrimRight(base64.StdEncoding.EncodeToString(encodedPassword), "=")
}
func EncyptSecret(secret string, key string) (string, error) {
encyptedSecret, err := AESGCMEncrypt(MD5Encode([]byte(key)), []byte(secret)) // md5encode make the aes key's length to 16
// EncryptSecret returns a encrypted secret
func EncryptSecret(secret string, key string) (string, error) {
encryptedSecret, err := AESGCMEncrypt(MD5Encode([]byte(key)), []byte(secret)) // md5encode make the aes key's length to 16
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encyptedSecret), nil
return base64.StdEncoding.EncodeToString(encryptedSecret), nil
}
// DecryptSecret returns a decrypted secret
func DecryptSecret(encyptedSecret string, key string) (string, error) {
encyptedData, err := base64.StdEncoding.DecodeString(encyptedSecret)