Initial commit

This commit is contained in:
GeekROS
2024-03-03 22:59:18 +08:00
commit cec0aae8e3
69 changed files with 2687 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
package Utils
type EmptyData struct{}

View File

@@ -0,0 +1,27 @@
package Utils
import (
"Game/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,49 @@
package Utils
import "strings"
func CheckUserAgent(userAgent string) bool {
Status := false
if strings.Contains(userAgent, "GodotEngine") {
Status = true
}
return Status
}
func CheckGame(token string) (int, int, bool) {
Status := false
GameId := 0
GameAccountId := 0
if token != "" {
tokenMap, _ := DecodeId(128, token)
if len(tokenMap) == 2 {
GameId = tokenMap[0]
GameAccountId = tokenMap[1]
Status = true
}
}
if GameId == 0 || GameAccountId == 0 {
Status = false
}
return GameId, GameAccountId, Status
}
func CheckUser(token string) (int, bool) {
Status := false
Uid := 0
if token != "" {
tokenMap, _ := DecodeId(32, token)
if len(tokenMap) == 3 {
Uid = tokenMap[0]
Status = true
}
}
return Uid, Status
}

View File

@@ -0,0 +1,17 @@
package Utils
import "gopkg.in/gomail.v2"
func SendMail(to string, subject string, content string) bool {
status := true
mail := gomail.NewMessage()
mail.SetHeader("From", mail.FormatAddress("open@wileho.com", "GEEKROS"))
mail.SetHeader("To", to)
mail.SetHeader("Subject", subject)
mail.SetBody("text/html", content)
send := gomail.NewDialer("smtp.qq.com", 587, "open@wileho.com", "")
if err := send.DialAndSend(mail); err != nil {
status = false
}
return status
}

View File

@@ -0,0 +1,27 @@
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,22 @@
/**
******************************************************************************
* @file md5.go
* @author MakerYang
******************************************************************************
*/
package Utils
import (
"crypto/md5"
"encoding/hex"
)
func MD5Hash(text string) string {
hash := md5.Sum([]byte(text))
return hex.EncodeToString(hash[:])
}
func VerifyPassword(storedPassword, inputPassword string) bool {
return MD5Hash(inputPassword) == storedPassword
}

View File

@@ -0,0 +1,18 @@
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,69 @@
package Utils
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"regexp"
)
func MobileFormat(str string) string {
re, _ := regexp.Compile("(\\d{3})(\\d{6})(\\d{2})")
return re.ReplaceAllString(str, "$1******$3")
}
func SendMessage(form string, phone string, info string) bool {
status := true
if form == "" || phone == "" || info == "" {
status = false
return status
}
desc := ""
if form == "express" {
desc = "【GEEKROS】Hi" + info + " 你在GEEKROS的订单已经发货请留意快递信息及时查收。"
}
if form == "account" {
desc = "【GEEKROS】你的验证码为" + info + " 有效期10分钟工作人员绝不会索取此验证码切勿告知他人。"
}
apiUrl := "https://smssh1.253.com/msg/v1/send/json"
params := make(map[string]interface{})
params["account"] = ""
params["password"] = ""
params["phone"] = phone
params["msg"] = desc
params["report"] = "false"
bytesData, err := json.Marshal(params)
if err != nil {
status = false
return status
}
reader := bytes.NewReader(bytesData)
request, err := http.NewRequest("POST", apiUrl, reader)
if err != nil {
status = false
return status
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
status = false
return status
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
status = false
return status
}
log.Println("[PhoneMessage]", string(respBytes))
return true
}

View File

@@ -0,0 +1,7 @@
package Utils
import "fmt"
func PriceConvert(num int) string {
return fmt.Sprintf("%.2f", float64(num)/100)
}

View File

@@ -0,0 +1,20 @@
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,105 @@
package Utils
import (
"encoding/json"
"github.com/gin-gonic/gin"
"log"
"net/http"
"os"
"strconv"
"time"
)
type logData struct {
Timestamp int64 `json:"timestamp"`
TimestampFormat string `json:"timestamp_format"`
ClientMethod string `json:"client_method"`
ClientIp string `json:"client_ip"`
ClientParameter string `json:"client_parameter"`
ServerParameter string `json:"server_parameter"`
ServerUrl string `json:"server_url"`
ServerName string `json:"server_name"`
ServerYear string `json:"server_year"`
ServerMonth string `json:"server_month"`
ServerDay string `json:"server_day"`
ServerTime string `json:"server_time"`
TimeLength string `json:"time_length"`
}
func recordLog(c *gin.Context, serverParameter string) {
data := &logData{}
data.Timestamp = time.Now().Unix()
data.TimestampFormat = time.Now().Format("2006-01-02 15:04:05")
data.ClientMethod = c.Request.Method
data.ClientIp = c.ClientIP()
if data.ClientMethod == "GET" {
data.ClientParameter = c.Request.RequestURI
}
if data.ClientMethod == "POST" {
clientParam, err := json.Marshal(c.Request.PostForm)
if err != nil {
data.ClientParameter = ""
}
if err == nil {
data.ClientParameter = string(clientParam)
}
}
scheme := "http://"
if c.Request.TLS != nil {
scheme = "https://"
}
serverUrl := scheme + c.Request.Host + c.Request.URL.Path
serverName, _ := os.Hostname()
data.ServerUrl = serverUrl
data.ServerName = serverName
data.ClientParameter = c.GetString("client_parameter")
data.ServerParameter = serverParameter
data.ServerYear = time.Now().Format("2006")
data.ServerMonth = time.Now().Format("01")
data.ServerDay = time.Now().Format("02")
data.ServerTime = time.Now().Format("15:04:05")
data.TimeLength = strconv.FormatFloat(float64(time.Now().UnixNano())/1000000-c.GetFloat64("start_time"), 'f', 2, 64)
dataString, _ := json.Marshal(data)
log.Println("[Log]", string(dataString))
}
func Success(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": 0, "msg": "success", "data": data})
recordLog(c, string(logJson))
}
func Error(c *gin.Context, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": 10000,
"msg": "error",
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": 10000, "msg": "error", "data": data})
recordLog(c, string(logJson))
}
func Warning(c *gin.Context, code int, msg string, data interface{}) {
c.JSON(http.StatusOK, gin.H{
"code": code,
"msg": msg,
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": code, "msg": msg, "data": data})
recordLog(c, string(logJson))
}
func AuthError(c *gin.Context, code int, msg string, data interface{}) {
c.JSON(http.StatusUnauthorized, gin.H{
"code": code,
"msg": msg,
"data": data,
})
logJson, _ := json.Marshal(gin.H{"code": code, "msg": msg, "data": data})
recordLog(c, string(logJson))
}

View File

@@ -0,0 +1,33 @@
package Utils
import (
"strconv"
"time"
)
func TimeFormat(unix int) (string, string) {
timeInt := time.Unix(int64(unix), 0)
return timeInt.Format("2006年01月02日"), timeInt.Format("2006-01-02 15:04:05")
}
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
}