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
+1 -1
View File
@@ -86,7 +86,7 @@ func (s *TwoFactorAuthorizationService) CreateTwoFactorSetting(twoFactor *models
} }
var err error 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 { if err != nil {
return err return err
+2
View File
@@ -11,6 +11,7 @@ import (
"github.com/mayswind/lab/pkg/errs" "github.com/mayswind/lab/pkg/errs"
) )
// PrintSuccessResult writes success response to current http context
func PrintSuccessResult(c *core.Context, result interface{}) { func PrintSuccessResult(c *core.Context, result interface{}) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "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) { func PrintErrorResult(c *core.Context, err *errs.Error) {
c.SetResponseError(err) c.SetResponseError(err)
+8
View File
@@ -2,14 +2,18 @@ package utils
import "strconv" import "strconv"
// Int32ToString returns the textual representation of this number
func Int32ToString(num int) string { func Int32ToString(num int) string {
return strconv.Itoa(num) return strconv.Itoa(num)
} }
// StringToInt32 parses a textual representation of the number to int32
func StringToInt32(str string) (int, error) { func StringToInt32(str string) (int, error) {
return strconv.Atoi(str) 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 { func StringTryToInt32(str string, defaultValue int) int {
num, err := StringToInt32(str) num, err := StringToInt32(str)
@@ -20,14 +24,18 @@ func StringTryToInt32(str string, defaultValue int) int {
return num return num
} }
// Int64ToString returns the textual representation of this number
func Int64ToString(num int64) string { func Int64ToString(num int64) string {
return strconv.FormatInt(num, 10) return strconv.FormatInt(num, 10)
} }
// StringToInt64 parses a textual representation of the number to int64
func StringToInt64(str string) (int64, error) { func StringToInt64(str string) (int64, error) {
return strconv.ParseInt(str, 10, 64) 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 { func StringTryToInt64(str string, defaultValue int64) int64 {
num, err := StringToInt64(str) num, err := StringToInt64(str)
+10 -3
View File
@@ -2,24 +2,31 @@ package utils
import "time" 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 { 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) { 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 { func GetMinTransactionTimeFromUnixTime(unixTime int64) int64 {
return unixTime * 1000 return unixTime * 1000
} }
// GetMaxTransactionTimeFromUnixTime returns the maximum transaction time from unix time
func GetMaxTransactionTimeFromUnixTime(unixTime int64) int64 { func GetMaxTransactionTimeFromUnixTime(unixTime int64) int64 {
return unixTime*1000 + 999 return unixTime*1000 + 999
} }
// GetUnixTimeFromTransactionTime returns unix time from the transaction time
func GetUnixTimeFromTransactionTime(transactionTime int64) int64 { func GetUnixTimeFromTransactionTime(transactionTime int64) int64 {
return transactionTime / 1000 return transactionTime / 1000
} }
+2
View File
@@ -7,6 +7,7 @@ import (
"github.com/mayswind/lab/pkg/errs" "github.com/mayswind/lab/pkg/errs"
) )
// GetLocalIPAddressesString returns all local ip address, every ip split by comma
func GetLocalIPAddressesString() (string, error) { func GetLocalIPAddressesString() (string, error) {
localAddrs, err := GetLocalIPAddresses() localAddrs, err := GetLocalIPAddresses()
@@ -31,6 +32,7 @@ func GetLocalIPAddressesString() (string, error) {
return string(buff.Bytes()), nil return string(buff.Bytes()), nil
} }
// GetLocalIPAddresses returns all local ip address object array
func GetLocalIPAddresses() ([]net.IP, error) { func GetLocalIPAddresses() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs() addrs, err := net.InterfaceAddrs()
+1
View File
@@ -5,6 +5,7 @@ import (
"math/big" "math/big"
) )
// GetRandomInteger returns a random number, the max parameter represents upper limit
func GetRandomInteger(max int) (int, error) { func GetRandomInteger(max int) (int, error) {
result, err := rand.Int(rand.Reader, big.NewInt(int64(max))) result, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
+1
View File
@@ -5,6 +5,7 @@ import (
"encoding/gob" "encoding/gob"
) )
// Clone deep-clones src object to dst object
func Clone(src, dst interface{}) error { func Clone(src, dst interface{}) error {
var buf bytes.Buffer var buf bytes.Buffer
+9 -6
View File
@@ -3,19 +3,22 @@ package utils
import "regexp" import "regexp"
var ( var (
UsernamePattern = regexp.MustCompile("^(?i)[a-z0-9_-]+$") 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])+)\\])$") 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})$") hexRGBColorPattern = regexp.MustCompile("^(?i)([0-9a-f]{6}|[0-9a-f]{3})$")
) )
// IsValidUsername reports whether username is valid
func IsValidUsername(username string) bool { func IsValidUsername(username string) bool {
return UsernamePattern.MatchString(username) return usernamePattern.MatchString(username)
} }
// IsValidEmail reports whether email is valid
func IsValidEmail(email string) bool { func IsValidEmail(email string) bool {
return EmailPattern.MatchString(email) return emailPattern.MatchString(email)
} }
// IsValidHexRGBColor reports whether color is valid
func IsValidHexRGBColor(color string) bool { func IsValidHexRGBColor(color string) bool {
return HexRGBColorPattern.MatchString(color) return hexRGBColorPattern.MatchString(color)
} }
+2
View File
@@ -1,5 +1,6 @@
package utils package utils
// Int64SliceMinus returns a int64 array which contains items in s1 but not in s2
func Int64SliceMinus(s1, s2 []int64) []int64 { func Int64SliceMinus(s1, s2 []int64) []int64 {
if s1 == nil { if s1 == nil {
return nil return nil
@@ -21,6 +22,7 @@ func Int64SliceMinus(s1, s2 []int64) []int64 {
return ret return ret
} }
// ToUniqueInt64Slice returns a int64 array which does not have duplicated items
func ToUniqueInt64Slice(items []int64) []int64 { func ToUniqueInt64Slice(items []int64) []int64 {
uniqueItems := make([]int64, 0, len(items)) uniqueItems := make([]int64, 0, len(items))
itemExistMap := make(map[int64]bool) itemExistMap := make(map[int64]bool)
+13 -3
View File
@@ -22,6 +22,7 @@ const (
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS) 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 { func SubString(str string, start int, length int) string {
chars := []rune(str) chars := []rune(str)
realLength := len(chars) realLength := len(chars)
@@ -55,6 +56,7 @@ func SubString(str string, start int, length int) string {
return string(chars[start:end]) return string(chars[start:end])
} }
// GetFirstLowerCharString returns the source string parameter, but makes the first character lower case
func GetFirstLowerCharString(s string) string { func GetFirstLowerCharString(s string) string {
if s == "" { if s == "" {
return s return s
@@ -70,6 +72,7 @@ func GetFirstLowerCharString(s string) string {
return string(chars) return string(chars)
} }
// GetRandomString returns a random string of which length is n
func GetRandomString(n int) (string, error) { func GetRandomString(n int) (string, error) {
var result = make([]byte, n) var result = make([]byte, n)
@@ -86,6 +89,7 @@ func GetRandomString(n int) (string, error) {
return string(result), nil return string(result), nil
} }
// GetRandomNumberOrLetter returns a random string which only contains number or letter characters
func GetRandomNumberOrLetter(n int) (string, error) { func GetRandomNumberOrLetter(n int) (string, error) {
var result = make([]byte, n) var result = make([]byte, n)
@@ -102,12 +106,14 @@ func GetRandomNumberOrLetter(n int) (string, error) {
return string(result), nil return string(result), nil
} }
// MD5Encode returns a hashed string by md5
func MD5Encode(data []byte) []byte { func MD5Encode(data []byte) []byte {
m := md5.New() m := md5.New()
m.Write(data) m.Write(data)
return m.Sum(nil) return m.Sum(nil)
} }
// AESGCMEncrypt returns a encrypted string by aes-gcm
func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) { func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
@@ -133,6 +139,7 @@ func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
return result, nil return result, nil
} }
// AESGCMEncrypt returns a decrypted string by aes-gcm
func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) { func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key) block, err := aes.NewCipher(key)
@@ -164,21 +171,24 @@ func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
return plainText, nil return plainText, nil
} }
// EncodePassword returns a encoded password
func EncodePassword(password string, salt string) string { func EncodePassword(password string, salt string) string {
encodedPassword := pbkdf2.Key([]byte(password), []byte(salt), 10000, 48, sha256.New) // 256^48 = 64^64 encodedPassword := pbkdf2.Key([]byte(password), []byte(salt), 10000, 48, sha256.New) // 256^48 = 64^64
return strings.TrimRight(base64.StdEncoding.EncodeToString(encodedPassword), "=") return strings.TrimRight(base64.StdEncoding.EncodeToString(encodedPassword), "=")
} }
func EncyptSecret(secret string, key string) (string, error) { // EncryptSecret returns a encrypted secret
encyptedSecret, err := AESGCMEncrypt(MD5Encode([]byte(key)), []byte(secret)) // md5encode make the aes key's length to 16 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 { if err != nil {
return "", err 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) { func DecryptSecret(encyptedSecret string, key string) (string, error) {
encyptedData, err := base64.StdEncoding.DecodeString(encyptedSecret) encyptedData, err := base64.StdEncoding.DecodeString(encyptedSecret)