This commit is contained in:
MakerYang
2024-08-06 18:30:21 +08:00
parent f363be1fc8
commit a902dd3de7
1870 changed files with 496402 additions and 6524 deletions

View File

@@ -0,0 +1,10 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
type EmptyData struct{}

View File

@@ -0,0 +1,46 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"Service/framework/config"
"github.com/speps/go-hashids"
)
func EncodeId(len int, id ...int) string {
hd := hashids.NewData()
hd.Salt = Config.Get.Hash.Salt
hd.MinLength = len
h := hashids.NewWithData(hd)
e, _ := h.Encode(id)
return e
}
func DecodeId(len int, encodedId string) ([]int, error) {
hd := hashids.NewData()
hd.Salt = Config.Get.Hash.Salt
hd.MinLength = len
h := hashids.NewWithData(hd)
d, err := h.DecodeWithError(encodedId)
if err != nil {
return nil, err
}
return d, nil
}

View File

@@ -0,0 +1,41 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"github.com/gin-gonic/gin"
"strings"
)
func CheckHeader(c *gin.Context) (bool, int) {
status := false
accountUID := 0
referer := c.Request.Header.Get("Accept-Fetch-Referer")
if referer != "" {
allowedReferer := []string{
"makeryang.com",
}
for _, allowedReferer := range allowedReferer {
if strings.HasPrefix(referer, allowedReferer) {
status = true
}
}
}
auth := c.Request.Header.Get("Accept-Fetch-Auth")
if auth != "" {
uidMap, _ := DecodeId(128, auth)
if len(uidMap) > 0 {
accountUID = uidMap[0]
}
}
return status, accountUID
}

View File

@@ -0,0 +1,38 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"github.com/russross/blackfriday"
"regexp"
"strings"
)
func TrimHtml(html string) string {
//将HTML标签全转换成小写
re, _ := regexp.Compile("<[\\S\\s]+?>")
html = re.ReplaceAllStringFunc(html, strings.ToLower)
//去除STYLE
re, _ = regexp.Compile("<style[\\S\\s]+?</style>")
html = re.ReplaceAllString(html, "")
//去除SCRIPT
re, _ = regexp.Compile("<script[\\S\\s]+?</script>")
html = re.ReplaceAllString(html, "")
//去除所有尖括号内的HTML代码并换成换行符
re, _ = regexp.Compile("<[\\S\\s]+?>")
html = re.ReplaceAllString(html, "\n")
//去除连续的换行符
re, _ = regexp.Compile("\\s{2,}")
html = re.ReplaceAllString(html, "\n")
return strings.TrimSpace(html)
}
func Markdown2Html(markdown string) string {
html := blackfriday.MarkdownCommon([]byte(markdown))
return string(html)
}

View File

@@ -0,0 +1,51 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"gopkg.in/gomail.v2"
"strings"
)
func MailFormat(email string) string {
atIndex := strings.Index(email, "@")
if atIndex == -1 {
return email
}
prefixLength := 2
if atIndex < prefixLength {
prefixLength = atIndex
}
prefix := email[:prefixLength]
starsCount := atIndex - prefixLength
if starsCount < 0 {
starsCount = 0
}
hiddenPart := strings.Repeat("*", starsCount)
domain := email[atIndex:]
return prefix + hiddenPart + domain
}
func SendMail(to string, subject string, content string) bool {
status := true
mail := gomail.NewMessage()
mail.SetHeader("From", mail.FormatAddress("makeryangcom@foxmail.com", "MakerYang"))
mail.SetHeader("To", to)
mail.SetHeader("Subject", subject)
mail.SetBody("text/html", content)
send := gomail.NewDialer("smtp.qq.com", 587, "makeryangcom@foxmail.com", "xwaacdrftozsbjgc")
if err := send.DialAndSend(mail); err != nil {
status = false
}
return status
}

View File

@@ -0,0 +1,34 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"regexp"
"strings"
)
func FilterMarkdown(input string) string {
quoteBlockRegex := regexp.MustCompile(`^\s*>[ \t]*(.*)$`)
lines := strings.Split(input, "\n")
var quoteLines []string
for _, line := range lines {
if quoteBlockRegex.MatchString(line) {
match := quoteBlockRegex.FindStringSubmatch(line)
quoteLines = append(quoteLines, match[1])
}
}
return strings.Join(quoteLines, "")
}
func FilterSummary(input string, maxLength int) string {
text := strings.TrimSpace(input)
if len(text) <= maxLength {
return text
}
return text[:maxLength]
}

View File

@@ -0,0 +1,45 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"fmt"
"strings"
)
func FormatKUnit(number int) string {
if number < 1000 {
return fmt.Sprintf("%d", number)
}
kValue := float64(number) / 1000.0
return fmt.Sprintf("%.1fK", kValue)
}
func FormatCurrency(amount int) string {
amountStr := fmt.Sprintf("%d", amount)
runes := []rune(amountStr)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
revStr := string(runes)
var result strings.Builder
for i, r := range revStr {
if i > 0 && i%3 == 0 {
result.WriteRune(',')
}
result.WriteRune(r)
}
runes = []rune(result.String())
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

View File

@@ -0,0 +1,31 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"math/rand"
"time"
)
func CreateOrderNum() string {
str := "0123456789"
bytes := []byte(str)
result := make([]byte, 0)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 8; i++ {
result = append(result, bytes[r.Intn(len(bytes))])
}
order := time.Now().Format("20060102150405") + string(result)
return order
}

View File

@@ -0,0 +1,20 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"crypto/md5"
"encoding/hex"
)
func EncryptMD5(input string) string {
hash := md5.New()
hash.Write([]byte(input))
hashBytes := hash.Sum(nil)
return hex.EncodeToString(hashBytes)
}

View File

@@ -0,0 +1,119 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"regexp"
"time"
)
func MobileFormat(str string) string {
re, _ := regexp.Compile("(\\d{3})(\\d{6})(\\d{2})")
return re.ReplaceAllString(str, "$1******$3")
}
type SendSmsRequest struct {
PhoneNumberSet []string `json:"PhoneNumberSet,omitempty"`
SmsSdkAppId string `json:"SmsSdkAppId,omitempty"`
TemplateId string `json:"TemplateId,omitempty"`
SignName string `json:"SignName,omitempty"`
TemplateParamSet []string `json:"TemplateParamSet,omitempty"`
ExtendCode string `json:"ExtendCode,omitempty"`
SessionContext string `json:"SessionContext,omitempty"`
SenderId string `json:"SenderId,omitempty"`
}
func sha256hex(s string) string {
b := sha256.Sum256([]byte(s))
return hex.EncodeToString(b[:])
}
func hmacsha256(s, key string) string {
hashed := hmac.New(sha256.New, []byte(key))
hashed.Write([]byte(s))
return string(hashed.Sum(nil))
}
func SendMessage(form string, phone string, info string) bool {
status := true
secretId := ""
secretKey := ""
host := "sms.tencentcloudapi.com"
algorithm := "TC3-HMAC-SHA256"
service := "sms"
version := "2021-01-11"
action := "SendSms"
region := "ap-guangzhou"
timestamp := time.Now().Unix()
httpRequestMethod := "POST"
canonicalURI := "/"
canonicalQueryString := ""
canonicalHeaders := "content-type:application/json; charset=utf-8\n" + "host:" + host + "\n"
signedHeaders := "content-type;host"
request := SendSmsRequest{
SmsSdkAppId: "",
SignName: "MakerYang",
TemplateId: "665293",
TemplateParamSet: []string{info, "5"},
PhoneNumberSet: []string{"+86" + phone},
SessionContext: "{1}为您的验证码,请于{2}分钟内填写。如非本人操作,请忽略本短信。",
}
payload, _ := json.Marshal(request)
hashedRequestPayload := sha256hex(string(payload))
canonicalRequest := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s", httpRequestMethod, canonicalURI, canonicalQueryString, canonicalHeaders, signedHeaders, hashedRequestPayload)
date := time.Unix(timestamp, 0).UTC().Format("2006-01-02")
credentialScope := fmt.Sprintf("%s/%s/tc3_request", date, service)
hashedCanonicalRequest := sha256hex(canonicalRequest)
string2sign := fmt.Sprintf("%s\n%d\n%s\n%s", algorithm, timestamp, credentialScope, hashedCanonicalRequest)
secretDate := hmacsha256(date, "TC3"+secretKey)
secretService := hmacsha256(service, secretDate)
secretSigning := hmacsha256("tc3_request", secretService)
signature := hex.EncodeToString([]byte(hmacsha256(string2sign, secretSigning)))
authorization := fmt.Sprintf("%s Credential=%s/%s, SignedHeaders=%s, Signature=%s", algorithm, secretId, credentialScope, signedHeaders, signature)
url := fmt.Sprintf("https://%s", host)
req, err := http.NewRequest("POST", url, bytes.NewBufferString(string(payload)))
if err != nil {
status = false
return status
}
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
req.Header.Set("Host", host)
req.Header.Set("X-TC-Action", action)
req.Header.Set("X-TC-Timestamp", fmt.Sprintf("%d", timestamp))
req.Header.Set("X-TC-Version", version)
req.Header.Set("X-TC-Region", region)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
status = false
return status
}
defer resp.Body.Close()
return true
}

View File

@@ -0,0 +1,14 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import "fmt"
func PriceConvert(num int) string {
return fmt.Sprintf("%.2f", float64(num)/100)
}

View File

@@ -0,0 +1,27 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"fmt"
"math/rand"
"time"
)
func RandInt(min, max int) int {
if min >= max || min == 0 || max == 0 {
return max
}
return rand.Intn(max-min) + min
}
func RandCode() string {
randNumber := rand.New(rand.NewSource(time.Now().UnixNano()))
code := fmt.Sprintf("%06v", randNumber.Int31n(1000000))
return code
}

View File

@@ -0,0 +1,137 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"log"
"math"
"net/http"
"os"
"strconv"
"time"
)
type logData struct {
ClientIp string `json:"client_ip"`
ClientMethod string `json:"client_method"`
ClientUrl string `json:"client_url"`
AcceptFetchId string `json:"accept_fetch_id"`
AcceptFetchReferer string `json:"accept_fetch_referer"`
AcceptFetchVisitor string `json:"accept_fetch_visitor"`
AcceptFetchAuth string `json:"accept_fetch_auth"`
ClientParameter clientParameter `json:"client_parameter"`
ServerParameter string `json:"server_parameter"`
Date string `json:"date"`
Time int64 `json:"time"`
Server string `json:"server"`
Length string `json:"length"`
}
type clientParameter struct {
Get interface{} `json:"get"`
Post interface{} `json:"post"`
}
func requestLog(c *gin.Context, serverParameter string) {
data := &logData{}
data.Time = time.Now().Unix()
data.Date = time.Now().Format("2006-01-02 15:04:05")
data.ClientMethod = c.Request.Method
data.ClientIp = c.ClientIP()
data.AcceptFetchId = c.Request.Header.Get("Accept-Fetch-Id")
data.AcceptFetchReferer = c.Request.Header.Get("Accept-Fetch-Referer")
data.AcceptFetchVisitor = c.Request.Header.Get("Accept-Fetch-Visitor")
data.AcceptFetchAuth = c.Request.Header.Get("Accept-Fetch-Auth")
if data.ClientMethod == "GET" {
data.ClientParameter.Get = c.Request.URL.Query()
}
if data.ClientMethod == "POST" {
data.ClientParameter.Post = c.Request.PostForm
}
scheme := "http://"
if c.Request.TLS != nil {
scheme = "https://"
}
serverUrl := scheme + c.Request.Host + c.Request.URL.Path
data.ClientUrl = serverUrl
serverName, _ := os.Hostname()
data.Server = serverName
data.ServerParameter = serverParameter
clientTimeStr := c.Request.Header.Get("Client-Time")
if clientTimeStr != "" {
clientTimeMs, _ := strconv.ParseInt(clientTimeStr, 10, 64)
serverTimeMs := time.Now().UnixNano() / 1e6
processingTimeMs := serverTimeMs - clientTimeMs
data.Length = fmt.Sprintf("%.3f", math.Abs(float64(processingTimeMs)/1000.0))
}
dataString, _ := json.Marshal(data)
log.Println("[request]", string(dataString))
}
func Success(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"message": "success",
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": 0, "msg": "success", "message": "success", "data": data})
requestLog(c, string(logJson))
}
func Error(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": 10000,
"msg": "error",
"message": "error",
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": 10000, "msg": "error", "message": "error", "data": data})
requestLog(c, string(logJson))
}
func Warning(c *gin.Context, code int, msg string, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": code,
"msg": msg,
"message": msg,
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": code, "msg": msg, "message": msg, "data": data})
requestLog(c, string(logJson))
}
func AuthError(c *gin.Context, code int, msg string, data interface{}) {
c.JSON(http.StatusUnauthorized, gin.H{
"code": code,
"msg": msg,
"message": msg,
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": code, "msg": msg, "message": msg, "data": data})
requestLog(c, string(logJson))
}

View File

@@ -0,0 +1,80 @@
/**
#*****************************************************************************
# @author MakerYang
# @site mir2.makeryang.com
#*****************************************************************************
*/
package Utils
import (
"fmt"
"strconv"
"time"
)
func TimeFormat(unix int) (string, string) {
timeInt := time.Unix(int64(unix), 0)
return timeInt.Format("2006年01月02日 15:04:05"), timeInt.Format("2006-01-02 15:04:05")
}
func TimeMinFormat(unix int) (string, string) {
timeInt := time.Unix(int64(unix), 0)
return timeInt.Format("2006年01月02日"), timeInt.Format("2006-01-02")
}
func DateFormat(times int) string {
createTime := time.Unix(int64(times), 0)
now := time.Now().Unix()
difTime := now - int64(times)
str := ""
if difTime < 60 {
str = "刚刚"
} else if difTime < 3600 {
M := difTime / 60
str = strconv.Itoa(int(M)) + "分钟前"
} else if difTime < 3600*24 {
H := difTime / 3600
str = strconv.Itoa(int(H)) + "小时前"
} else {
str = createTime.Format("2006-01-02 15:04:05")
}
return str
}
func DateFormatFine(timestamp int64) string {
now := time.Now()
past := time.Unix(timestamp, 0) // Convert Unix timestamp to time.Time
duration := now.Sub(past)
// Calculate the differences
seconds := int(duration.Seconds())
minutes := int(duration.Minutes())
hours := int(duration.Hours())
days := hours / 24
weeks := days / 7
// months := days / 30
switch {
case seconds < 60:
return fmt.Sprintf("%d 秒前", seconds)
case minutes < 60:
return fmt.Sprintf("%d 分钟前", minutes)
case hours < 24:
return fmt.Sprintf("%d 小时前", hours)
case days < 7:
return fmt.Sprintf("%d 天前", days)
case days < 30:
return fmt.Sprintf("%d 周前", weeks)
default:
return past.Format("2006年01月02日")
}
}