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,52 @@
/**
******************************************************************************
* @file config.go
* @author MakerYang
******************************************************************************
*/
package Config
import "time"
var Get = &config{}
type config struct {
Service service `json:"service"`
Database database `json:"database"`
Hash hash `json:"hash"`
}
type service struct {
Mode string `json:"mode"`
HttpPort int `json:"http_port"`
ReadTimeout time.Duration `json:"read_timeout"`
WriteTimeout time.Duration `json:"write_timeout"`
}
type database struct {
Type string `json:"type"`
User string `json:"user"`
Password string `json:"password"`
Host string `json:"host"`
Name string `json:"name"`
}
type hash struct {
Salt string `json:"salt"`
}
func Init() {
Get.Service.Mode = "debug"
Get.Service.HttpPort = 7000
Get.Service.ReadTimeout = 60 * time.Second
Get.Service.WriteTimeout = 60 * time.Second
Get.Database.Name = "database"
Get.Database.Type = "mysql"
Get.Database.Host = "localhost"
Get.Database.User = "root"
Get.Database.Password = "88888888"
Get.Hash.Salt = "game_$@#godot_@$salt_$@$service%#^#%@%#"
}

View File

@@ -0,0 +1,61 @@
/**
******************************************************************************
* @file controller.go
* @author MakerYang
******************************************************************************
*/
package Controller
import (
"Game/framework/config"
"Game/framework/controller/ping"
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/gookit/color"
"log"
"net/http"
"os"
"os/signal"
"time"
)
func router() *gin.Engine {
router := gin.New()
gin.SetMode(Config.Get.Service.Mode)
router.GET("/ping", PingController.Ping)
return router
}
func Init() {
routers := router()
var HttpServer = &http.Server{
Addr: fmt.Sprintf(":%d", Config.Get.Service.HttpPort),
Handler: routers,
ReadTimeout: Config.Get.Service.ReadTimeout,
WriteTimeout: Config.Get.Service.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
go func() {
if err := HttpServer.ListenAndServe(); err != nil {
}
}()
log.Println("[game]", color.Green.Text("server..."))
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := HttpServer.Shutdown(ctx); err != nil {
}
}

View File

@@ -0,0 +1,18 @@
/**
******************************************************************************
* @file ping.go
* @author MakerYang
******************************************************************************
*/
package PingController
import (
"Game/framework/utils"
"github.com/gin-gonic/gin"
)
func Ping(c *gin.Context) {
Utils.Success(c, Utils.EmptyData{})
return
}

View File

@@ -0,0 +1,74 @@
/**
******************************************************************************
* @file database.go
* @author MakerYang
******************************************************************************
*/
package Database
import (
"Game/framework/config"
"fmt"
"github.com/gookit/color"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"time"
)
var Get *gorm.DB
type DefaultField struct {
CreateAt int `gorm:"Column:create_at" json:"create_at"`
UpdateAt int `gorm:"Column:update_at" json:"update_at"`
DeleteAt int `gorm:"Column:delete_at" json:"delete_at"`
}
func Init() {
var err error
Get, err = gorm.Open(Config.Get.Database.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", Config.Get.Database.User, Config.Get.Database.Password, Config.Get.Database.Host, Config.Get.Database.Name))
if err != nil {
log.Println("[database]", color.Red.Text(err.Error()))
}
if Config.Get.Service.Mode == "release" {
Get.LogMode(false)
} else {
Get.LogMode(true)
}
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return defaultTableName
}
Get.SingularTable(true)
Get.Callback().Create().Replace("gorm:update_time_stamp", func(scope *gorm.Scope) {
if !scope.HasError() {
nowTime := time.Now().Unix()
if createTimeField, ok := scope.FieldByName("CreateAt"); ok {
if createTimeField.IsBlank {
err := createTimeField.Set(nowTime)
if err != nil {
}
}
}
if modifyTimeField, ok := scope.FieldByName("UpdateAt"); ok {
if modifyTimeField.IsBlank {
err := modifyTimeField.Set(nowTime)
if err != nil {
}
}
}
}
})
Get.DB().SetMaxIdleConns(1000)
Get.DB().SetMaxOpenConns(10000)
Get.DB().SetConnMaxLifetime(time.Second * 45)
}

View File

@@ -0,0 +1,65 @@
/**
******************************************************************************
* @file interface.go
* @author MakerYang
******************************************************************************
*/
package Database
import (
"github.com/jinzhu/gorm"
"time"
)
type Base struct {
TableName string
}
func New(table string) *Base {
return &Base{
TableName: table,
}
}
func (base *Base) CreateData(data interface{}) error {
err := Get.Table(base.TableName).Create(data).Error
return err
}
func (base *Base) UpdateData(query interface{}, data map[string]interface{}) error {
data["update_at"] = time.Now().Unix()
err := Get.Table(base.TableName).Where(query).Updates(data).Error
return err
}
func (base *Base) ExprData(query interface{}, field string, operation string, data int) error {
err := Get.Table(base.TableName).Where(query).Update(field, gorm.Expr(field+" "+operation+" ?", data)).Error
return err
}
func (base *Base) GetData(dataStruct interface{}, query interface{}, order string) error {
err := Get.Table(base.TableName).Where(query).Order(order).First(dataStruct).Error
return err
}
func (base *Base) ListData(dataStruct interface{}, query interface{}, order string, limit int) error {
err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Find(dataStruct).Error
return err
}
func (base *Base) PageData(dataStruct interface{}, query interface{}, order string, limit int, page int) error {
err := Get.Table(base.TableName).Where(query).Order(order).Limit(limit).Offset(page * limit).Find(dataStruct).Error
return err
}
func (base *Base) CountData(query interface{}) (int, error) {
count := 0
err := Get.Table(base.TableName).Where(query).Count(&count).Error
return count, err
}
func (base *Base) DeleteData(dataStruct interface{}, query interface{}) error {
err := Get.Table(base.TableName).Where(query).Delete(dataStruct).Error
return err
}

View File

@@ -0,0 +1,23 @@
/**
******************************************************************************
* @file framework.go
* @author MakerYang
******************************************************************************
*/
package Framework
import (
"Game/framework/config"
"Game/framework/controller"
"Game/framework/database"
)
func Init() {
// 初始化配置
Config.Init()
// 初始化数据库
Database.Init()
// 初始化控制器
Controller.Init()
}

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
}