From 17d1cd87192553a69edcf2cce24f344ae8f83e6b Mon Sep 17 00:00:00 2001 From: MaysWind Date: Wed, 23 Dec 2020 00:09:35 +0800 Subject: [PATCH] add comments, code refactor, fix typo --- pkg/services/twofactor_authorizations.go | 2 +- pkg/utils/api.go | 2 ++ pkg/utils/converter.go | 8 ++++++++ pkg/utils/datetimes.go | 13 ++++++++++--- pkg/utils/network.go | 2 ++ pkg/utils/numbers.go | 1 + pkg/utils/object.go | 1 + pkg/utils/regexps.go | 15 +++++++++------ pkg/utils/slices.go | 2 ++ pkg/utils/strings.go | 16 +++++++++++++--- 10 files changed, 49 insertions(+), 13 deletions(-) diff --git a/pkg/services/twofactor_authorizations.go b/pkg/services/twofactor_authorizations.go index 6fd60c2d..fd0a1d79 100644 --- a/pkg/services/twofactor_authorizations.go +++ b/pkg/services/twofactor_authorizations.go @@ -86,7 +86,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(twoFactor *models } var err error - twoFactor.Secret, err = utils.EncyptSecret(twoFactor.Secret, s.CurrentConfig().SecretKey) + twoFactor.Secret, err = utils.EncryptSecret(twoFactor.Secret, s.CurrentConfig().SecretKey) if err != nil { return err diff --git a/pkg/utils/api.go b/pkg/utils/api.go index a72319c2..b856eeb8 100644 --- a/pkg/utils/api.go +++ b/pkg/utils/api.go @@ -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) diff --git a/pkg/utils/converter.go b/pkg/utils/converter.go index 8ce2c93b..f5a5f4a8 100644 --- a/pkg/utils/converter.go +++ b/pkg/utils/converter.go @@ -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) diff --git a/pkg/utils/datetimes.go b/pkg/utils/datetimes.go index a00ba8c5..b51d6a90 100644 --- a/pkg/utils/datetimes.go +++ b/pkg/utils/datetimes.go @@ -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 } diff --git a/pkg/utils/network.go b/pkg/utils/network.go index 3e6535ea..62c44140 100644 --- a/pkg/utils/network.go +++ b/pkg/utils/network.go @@ -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() diff --git a/pkg/utils/numbers.go b/pkg/utils/numbers.go index a98157e4..7337408f 100644 --- a/pkg/utils/numbers.go +++ b/pkg/utils/numbers.go @@ -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))) diff --git a/pkg/utils/object.go b/pkg/utils/object.go index bbcce1e6..7e118689 100644 --- a/pkg/utils/object.go +++ b/pkg/utils/object.go @@ -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 diff --git a/pkg/utils/regexps.go b/pkg/utils/regexps.go index 30dea05e..19a54f19 100644 --- a/pkg/utils/regexps.go +++ b/pkg/utils/regexps.go @@ -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) } diff --git a/pkg/utils/slices.go b/pkg/utils/slices.go index 352d8233..5b1731f3 100644 --- a/pkg/utils/slices.go +++ b/pkg/utils/slices.go @@ -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) diff --git a/pkg/utils/strings.go b/pkg/utils/strings.go index 3a51efe0..efcfd0e8 100644 --- a/pkg/utils/strings.go +++ b/pkg/utils/strings.go @@ -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)