add core/error/util files

This commit is contained in:
MaysWind
2020-10-17 17:22:10 +08:00
parent e5953c9f17
commit 6ad0a02d44
25 changed files with 917 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
package utils
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"github.com/mayswind/lab/pkg/core"
"github.com/mayswind/lab/pkg/errs"
)
func PrintSuccessResult(c *core.Context, result interface{}) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": result,
})
}
func PrintErrorResult(c *core.Context, err *errs.Error) {
c.SetResponseError(err)
errorMessage := err.Error()
if err.Code() == errs.ErrIncompleteOrIncorrectSubmission.Code() && len(err.BaseError) > 0 {
validationErrors, ok := err.BaseError[0].(validator.ValidationErrors)
if ok {
for _, err := range validationErrors {
errorMessage = getValidationErrorText(err)
break
}
}
}
c.AbortWithStatusJSON(err.HttpStatusCode, gin.H{
"success": false,
"errorCode": err.Code(),
"errorMessage": errorMessage,
})
}
func getValidationErrorText(err validator.FieldError) string {
fieldName := GetFirstLowerCharString(err.Field())
switch err.Tag() {
case "required":
return errs.GetParameterIsRequiredMessage(fieldName)
case "max":
return errs.GetParameterMustLessThanMessage(fieldName, err.Param())
case "min":
return errs.GetParameterMustMoreThanMessage(fieldName, err.Param())
case "len":
return errs.GetParameterLengthNotEqualMessage(fieldName, err.Param())
case "notBlank":
return errs.GetParameterNotBeBlankMessage(fieldName)
case "validUsername":
return errs.GetParameterInvalidUsernameMessage(fieldName)
case "validEmail":
return errs.GetParameterInvalidEmailMessage(fieldName)
}
return errs.GetParameterInvalidMessage(fieldName)
}
+39
View File
@@ -0,0 +1,39 @@
package utils
import "strconv"
func Int32ToString(num int) string {
return strconv.Itoa(num)
}
func StringToInt32(str string) (int, error) {
return strconv.Atoi(str)
}
func StringTryToInt32(str string, defaultValue int) int {
num, err := StringToInt32(str)
if err != nil {
return defaultValue
}
return num
}
func Int64ToString(num int64) string {
return strconv.FormatInt(num, 10)
}
func StringToInt64(str string) (int64, error) {
return strconv.ParseInt(str, 10, 64)
}
func StringTryToInt64(str string, defaultValue int64) int64 {
num, err := StringToInt64(str)
if err != nil {
return defaultValue
}
return num
}
+7
View File
@@ -0,0 +1,7 @@
package utils
import "time"
func FormatToLongDateTime(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
+62
View File
@@ -0,0 +1,62 @@
package utils
import (
"bytes"
"net"
"github.com/mayswind/lab/pkg/errs"
)
func GetLocalIPAddressesString() (string, error) {
localAddrs, err := GetLocalIPAddresses()
if err != nil {
return "", err
}
if len(localAddrs) < 1 {
return "", errs.ErrGettingLocalAddress
}
buff := &bytes.Buffer{}
for i := 0; i < len(localAddrs); i++ {
if i > 0 {
buff.WriteString(",")
}
buff.WriteString(localAddrs[i].String())
}
return string(buff.Bytes()), nil
}
func GetLocalIPAddresses() ([]net.IP, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
var localAddrs []net.IP
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok {
if ipnet.IP.IsLoopback() {
continue
}
if ipnet.IP.IsLinkLocalUnicast() {
continue
}
ip := ipnet.IP.To16()
if ip != nil {
localAddrs = append(localAddrs, ip)
}
}
}
return localAddrs, nil
}
+16
View File
@@ -0,0 +1,16 @@
package utils
import (
"crypto/rand"
"math/big"
)
func GetRandomInteger(max int) (int, error) {
result, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0, err
}
return int(result.Int64()), nil
}
+16
View File
@@ -0,0 +1,16 @@
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])+)\\])$")
)
func IsValidUsername(username string) bool {
return UsernamePattern.MatchString(username)
}
func IsValidEmail(email string) bool {
return EmailPattern.MatchString(email)
}
+65
View File
@@ -0,0 +1,65 @@
package utils
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestIsValidUsername_ValidUserName(t *testing.T) {
username := "foobar"
expectedValue := true
actualValue := IsValidUsername(username)
assert.Equal(t, expectedValue, actualValue)
username = "--foo_bar--"
expectedValue = true
actualValue = IsValidUsername(username)
assert.Equal(t, expectedValue, actualValue)
}
func TestIsValidUsername_InvalidUserName(t *testing.T) {
username := "foo~bar~"
expectedValue := false
actualValue := IsValidUsername(username)
assert.Equal(t, expectedValue, actualValue)
}
func TestIsValidEmail_ValidEmail(t *testing.T) {
email := "foo@bar.com"
expectedValue := true
actualValue := IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
email = "foo@1.2.3.4"
expectedValue = true
actualValue = IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
email = "foo_bar@foo.bar"
expectedValue = true
actualValue = IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
}
func TestIsValidEmail_InvalidEmail(t *testing.T) {
email := "foo"
expectedValue := false
actualValue := IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
email = "@bar"
expectedValue = false
actualValue = IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
email = "foo@bar"
expectedValue = false
actualValue = IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
email = "foo@bar."
expectedValue = false
actualValue = IsValidEmail(email)
assert.Equal(t, expectedValue, actualValue)
}
+19
View File
@@ -0,0 +1,19 @@
package utils
func IsStringSliceEuqals(s1, s2 []string) bool {
if (s1 == nil) != (s2 == nil) {
return false
}
if len(s1) != len(s2) {
return false
}
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
return false
}
}
return true
}
+196
View File
@@ -0,0 +1,196 @@
package utils
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"strings"
"unicode"
"golang.org/x/crypto/pbkdf2"
"github.com/mayswind/lab/pkg/errs"
)
const (
CHARACTERS = "!#$&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"
NUMBER_AND_LETTERS = "0123456789abcdefghijklmnopqrstuvwxyz"
CHARACTERS_LENGTH = len(CHARACTERS)
NUMBER_AND_LETTERS_LENGTH = len(NUMBER_AND_LETTERS)
)
func SubString(str string, start int, length int) string {
chars := []rune(str)
realLength := len(chars)
end := 0
if start < 0 {
start = realLength - 1 + start
}
end = start + length
if start > end {
start, end = end, start
}
if start < 0 {
start = 0
}
if start > realLength {
start = realLength
}
if end < 0 {
end = 0
}
if end > realLength {
end = realLength
}
return string(chars[start:end])
}
func GetFirstLowerCharString(s string) string {
if s == "" {
return s
}
chars := []rune(s)
if unicode.IsLower(chars[0]) {
return s
}
chars[0] = unicode.ToLower(chars[0])
return string(chars)
}
func GetRandomString(n int) (string, error) {
var result = make([]byte, n)
for i := 0; i < n; i++ {
index, err := GetRandomInteger(CHARACTERS_LENGTH)
if err != nil {
return "", err
}
result[i] = CHARACTERS[index]
}
return string(result), nil
}
func GetRandomNumberOrLetter(n int) (string, error) {
var result = make([]byte, n)
for i := 0; i < n; i++ {
index, err := GetRandomInteger(NUMBER_AND_LETTERS_LENGTH)
if err != nil {
return "", err
}
result[i] = NUMBER_AND_LETTERS[index]
}
return string(result), nil
}
func MD5Encode(data []byte) []byte {
m := md5.New()
m.Write(data)
return m.Sum(nil)
}
func AESGCMEncrypt(key []byte, plainText []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := make([]byte, aesgcm.NonceSize())
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
ciphertext := aesgcm.Seal(nil, nonce, plainText, nil)
result := append(nonce, ciphertext...)
return result, nil
}
func AESGCMDecrypt(key []byte, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonceSize := aesgcm.NonceSize()
if len(ciphertext) - nonceSize <= 0 {
return nil, errs.ErrCiphertextInvalid
}
nonce := ciphertext[:nonceSize]
ciphertext = ciphertext[nonceSize:]
plainText, err := aesgcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
return plainText, nil
}
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
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(encyptedSecret), nil
}
func DecryptSecret(encyptedSecret string, key string) (string, error) {
encyptedData, err := base64.StdEncoding.DecodeString(encyptedSecret)
if err != nil {
return "", err
}
secret, err := AESGCMDecrypt(MD5Encode([]byte(key)), []byte(encyptedData))
if err != nil {
return "", err
}
return string(secret), nil
}