初始化项目文件

This commit is contained in:
2025-07-11 16:54:11 +08:00
parent 6bffd582a0
commit 39fedaac16
213 changed files with 16944 additions and 0 deletions

15
api_file/Dockerfile Normal file
View File

@ -0,0 +1,15 @@
FROM golang:1.22.4
RUN mkdir -p /web \
mkdir -p /web/logs
ENV GOPATH=/web
ENV GOPROXY=https://goproxy.cn,direct
WORKDIR $GOPATH/api_file
COPY . $GOPATH/api_file
RUN go build .
ENTRYPOINT ["./main"]

View File

@ -0,0 +1,11 @@
database:
dsn: web:Song1875.@tcp(43.154.168.226:3306)/web_vue?charset=utf8mb4&parseTime=True&loc=Local
prd: false
logs:
log: logs
nginx: logs/nginx
sys:
jwt: False
User: admin

31
api_file/config/config.go Normal file
View File

@ -0,0 +1,31 @@
package config
import (
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
"os"
)
// Config 公共参数
var Config settings
// InitConfig 配置初始化
func InitConfig(version string) error {
var file []byte
var err error
if version == "dev" {
file, err = os.ReadFile("./config/config.dev.yaml")
} else {
file, err = os.ReadFile("./config/config.prd.yaml")
}
if err != nil {
logrus.Errorln("Error reading config file:", err)
return err
}
err = yaml.Unmarshal(file, &Config)
if err != nil {
logrus.Errorln("Error parsing config file:", err)
return err
}
return nil
}

View File

@ -0,0 +1,11 @@
database:
dsn: web_prd:SongPrd1875.@tcp(43.154.168.226:3306)/web_prd?charset=utf8mb4&parseTime=True&loc=Local
prd: true
logs:
log: logs
nginx: logs/nginx
sys:
jwt: True
User:

21
api_file/config/type.d.go Normal file
View File

@ -0,0 +1,21 @@
package config
type settings struct {
Logs *logs `yaml:"logs"`
Database *database `yaml:"database"`
}
type logs struct {
Nginx string `yaml:"nginx"`
Log string `yaml:"log"`
}
type database struct {
Dsn string `yaml:"dsn"`
Prd bool `yaml:"prd"`
}
type sys struct {
Jwt string `yaml:"jwt"`
User string `yaml:"user"`
}

View File

@ -0,0 +1,48 @@
package database
import (
"github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"main/config"
"sync"
)
var instance *MysqlConnectionPool
var once sync.Once
var db *gorm.DB
var err error
// GetInstance 获取数据库连接池
func GetInstance() *MysqlConnectionPool {
once.Do(func() {
instance = &MysqlConnectionPool{}
})
return instance
}
// InitDataPool 数据库初始化连接
func (m *MysqlConnectionPool) InitDataPool() (isSuccess bool) {
dbConfig := config.Config.Database
if dbConfig.Prd {
db, err = gorm.Open(mysql.Open(dbConfig.Dsn), &gorm.Config{})
} else {
db, err = gorm.Open(mysql.Open(dbConfig.Dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
}
if err != nil {
logrus.Errorln("数据库配置失败:", err)
return false
}
return true
}
// GetMysqlDb 获取数据库连接
func (m *MysqlConnectionPool) GetMysqlDb() (dbCon *gorm.DB) {
return db
}
type MysqlConnectionPool struct {
}

65
api_file/go.mod Normal file
View File

@ -0,0 +1,65 @@
module main
go 1.22.4
require (
github.com/antonfisher/nested-logrus-formatter v1.3.1
github.com/golang-jwt/jwt/v4 v4.5.1
github.com/iris-contrib/middleware/jwt v0.0.0-20240502084239-34f27409ce72
github.com/kataras/iris/v12 v12.2.11
github.com/shopspring/decimal v1.4.0
github.com/sirupsen/logrus v1.9.3
gopkg.in/yaml.v3 v3.0.1
gorm.io/driver/mysql v1.5.7
gorm.io/gorm v1.25.10
)
require (
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 // indirect
github.com/CloudyKit/jet/v6 v6.2.0 // indirect
github.com/Joker/jade v1.1.3 // indirect
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 // indirect
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/flosch/pongo2/v4 v4.0.2 // indirect
github.com/go-sql-driver/mysql v1.7.0 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/iris-contrib/schema v0.0.6 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/kataras/blocks v0.0.8 // indirect
github.com/kataras/golog v0.1.11 // indirect
github.com/kataras/pio v0.0.13 // indirect
github.com/kataras/sitemap v0.0.6 // indirect
github.com/kataras/tunnel v0.0.4 // indirect
github.com/klauspost/compress v1.17.7 // indirect
github.com/mailgun/raymond/v2 v2.0.48 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/microcosm-cc/bluemonday v1.0.26 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/schollz/closestmatch v2.1.0+incompatible // indirect
github.com/tdewolff/minify/v2 v2.20.19 // indirect
github.com/tdewolff/parse/v2 v2.7.12 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
github.com/vmihailenco/msgpack/v5 v5.4.1 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/yosssi/ace v0.0.5 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)

207
api_file/go.sum Normal file
View File

@ -0,0 +1,207 @@
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53 h1:sR+/8Yb4slttB4vD+b9btVEnWgL3Q00OBTzVT8B9C0c=
github.com/CloudyKit/fastprinter v0.0.0-20200109182630-33d98a066a53/go.mod h1:+3IMCy2vIlbG1XG/0ggNQv0SvxCAIpPM5b1nCz56Xno=
github.com/CloudyKit/jet/v6 v6.2.0 h1:EpcZ6SR9n28BUGtNJSvlBqf90IpjeFr36Tizxhn/oME=
github.com/CloudyKit/jet/v6 v6.2.0/go.mod h1:d3ypHeIRNo2+XyqnGA8s+aphtcVpjP5hPwP/Lzo7Ro4=
github.com/Joker/hpp v1.0.0 h1:65+iuJYdRXv/XyN62C1uEmmOx3432rNG/rKlX6V7Kkc=
github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY=
github.com/Joker/jade v1.1.3 h1:Qbeh12Vq6BxURXT1qZBRHsDxeURB8ztcL6f3EXSGeHk=
github.com/Joker/jade v1.1.3/go.mod h1:T+2WLyt7VH6Lp0TRxQrUYEs64nRc83wkMQrfeIQKduM=
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06 h1:KkH3I3sJuOLP3TjA/dfr4NAY8bghDwnXiU7cTKxQqo0=
github.com/Shopify/goreferrer v0.0.0-20220729165902-8cddb4f5de06/go.mod h1:7erjKLwalezA0k99cWs5L11HWOAPNjdUZ6RxH1BXbbM=
github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU=
github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY=
github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M=
github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY=
github.com/antonfisher/nested-logrus-formatter v1.3.1 h1:NFJIr+pzwv5QLHTPyKz9UMEoHck02Q9L0FP13b/xSbQ=
github.com/antonfisher/nested-logrus-formatter v1.3.1/go.mod h1:6WTfyWFkBc9+zyBaKIqRrg/KwMqBbodBjgbHjDz7zjA=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs=
github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw=
github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo=
github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M=
github.com/flosch/pongo2/v4 v4.0.2 h1:gv+5Pe3vaSVmiJvh/BZa82b7/00YUGm0PIyVVLop0Hw=
github.com/flosch/pongo2/v4 v4.0.2/go.mod h1:B5ObFANs/36VwxxlgKpdchIJHMvHB562PW+BWPhwZD8=
github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang-jwt/jwt/v4 v4.5.1 h1:JdqV9zKUdtaa9gdPlywC3aeoEsR681PlKC+4F5gQgeo=
github.com/golang-jwt/jwt/v4 v4.5.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0 h1:4gjrh/PN2MuWCCElk8/I4OCKRKWCCo2zEct3VKCbibU=
github.com/gomarkdown/markdown v0.0.0-20240328165702-4d01890c35c0/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY=
github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk=
github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA=
github.com/iris-contrib/httpexpect/v2 v2.15.2 h1:T9THsdP1woyAqKHwjkEsbCnMefsAFvk8iJJKokcJ3Go=
github.com/iris-contrib/httpexpect/v2 v2.15.2/go.mod h1:JLDgIqnFy5loDSUv1OA2j0mb6p/rDhiCqigP22Uq9xE=
github.com/iris-contrib/middleware/jwt v0.0.0-20240502084239-34f27409ce72 h1:wbkA/QXv1RZmuY2iLvsgmHeiGq4DNvv2Rhj5PQ2oHTI=
github.com/iris-contrib/middleware/jwt v0.0.0-20240502084239-34f27409ce72/go.mod h1:hIyBTK1zUxUaC4Hu8Ba9Z70r2S5ET4+ZKNescqjXld0=
github.com/iris-contrib/schema v0.0.6 h1:CPSBLyx2e91H2yJzPuhGuifVRnZBBJ3pCOMbOvPZaTw=
github.com/iris-contrib/schema v0.0.6/go.mod h1:iYszG0IOsuIsfzjymw1kMzTL8YQcCWlm65f3wX8J5iA=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kataras/blocks v0.0.8 h1:MrpVhoFTCR2v1iOOfGng5VJSILKeZZI+7NGfxEh3SUM=
github.com/kataras/blocks v0.0.8/go.mod h1:9Jm5zx6BB+06NwA+OhTbHW1xkMOYxahnqTN5DveZ2Yg=
github.com/kataras/golog v0.1.11 h1:dGkcCVsIpqiAMWTlebn/ZULHxFvfG4K43LF1cNWSh20=
github.com/kataras/golog v0.1.11/go.mod h1:mAkt1vbPowFUuUGvexyQ5NFW6djEgGyxQBIARJ0AH4A=
github.com/kataras/iris/v12 v12.2.11 h1:sGgo43rMPfzDft8rjVhPs6L3qDJy3TbBrMD/zGL1pzk=
github.com/kataras/iris/v12 v12.2.11/go.mod h1:uMAeX8OqG9vqdhyrIPv8Lajo/wXTtAF43wchP9WHt2w=
github.com/kataras/pio v0.0.13 h1:x0rXVX0fviDTXOOLOmr4MUxOabu1InVSTu5itF8CXCM=
github.com/kataras/pio v0.0.13/go.mod h1:k3HNuSw+eJ8Pm2lA4lRhg3DiCjVgHlP8hmXApSej3oM=
github.com/kataras/sitemap v0.0.6 h1:w71CRMMKYMJh6LR2wTgnk5hSgjVNB9KL60n5e2KHvLY=
github.com/kataras/sitemap v0.0.6/go.mod h1:dW4dOCNs896OR1HmG+dMLdT7JjDk7mYBzoIRwuj5jA4=
github.com/kataras/tunnel v0.0.4 h1:sCAqWuJV7nPzGrlb0os3j49lk2JhILT0rID38NHNLpA=
github.com/kataras/tunnel v0.0.4/go.mod h1:9FkU4LaeifdMWqZu7o20ojmW4B7hdhv2CMLwfnHGpYw=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mailgun/raymond/v2 v2.0.48 h1:5dmlB680ZkFG2RN/0lvTAghrSxIESeu9/2aeDqACtjw=
github.com/mailgun/raymond/v2 v2.0.48/go.mod h1:lsgvL50kgt1ylcFJYZiULi5fjPBkkhNfj4KA0W54Z18=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58=
github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sanity-io/litter v1.5.5 h1:iE+sBxPBzoK6uaEP5Lt3fHNgpKcHXc/A2HGETy0uJQo=
github.com/sanity-io/litter v1.5.5/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U=
github.com/schollz/closestmatch v2.1.0+incompatible h1:Uel2GXEpJqOWBrlyI+oY9LTiyyjYS17cCYRqP13/SHk=
github.com/schollz/closestmatch v2.1.0+incompatible/go.mod h1:RtP1ddjLong6gTkbtmuhtR2uUrrJOpYzYRvbcPAid+g=
github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=
github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=
github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tdewolff/minify/v2 v2.20.19 h1:tX0SR0LUrIqGoLjXnkIzRSIbKJ7PaNnSENLD4CyH6Xo=
github.com/tdewolff/minify/v2 v2.20.19/go.mod h1:ulkFoeAVWMLEyjuDz1ZIWOA31g5aWOawCFRp9R/MudM=
github.com/tdewolff/parse/v2 v2.7.12 h1:tgavkHc2ZDEQVKy1oWxwIyh5bP4F5fEh/JmBwPP/3LQ=
github.com/tdewolff/parse/v2 v2.7.12/go.mod h1:3FbJWZp3XT9OWVN3Hmfp0p/a08v4h8J9W1aghka0soA=
github.com/tdewolff/test v1.0.11-0.20231101010635-f1265d231d52/go.mod h1:6DAvZliBAAnD7rhVgwaM7DE5/d9NMOAJ09SqYqeK4QE=
github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739 h1:IkjBCtQOOjIn03u/dMQK9g+Iw9ewps4mCl1nB8Sscbo=
github.com/tdewolff/test v1.0.11-0.20240106005702-7de5f7df4739/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IUPn0Bjt8=
github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY=
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI=
github.com/yosssi/ace v0.0.5 h1:tUkIP/BLdKqrlrPwcmH0shwEEhTRHoGnc1wFIWmaBUA=
github.com/yosssi/ace v0.0.5/go.mod h1:ALfIzm2vT7t5ZE7uoIZqF3TQ7SAOyupFZnkrF5id+K0=
github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA=
github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M=
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0 h1:985EYyeCOxTpcgOTJpflJUwOeEz0CQOdPt73OzpE9F8=
golang.org/x/exp v0.0.0-20240404231335-c0f41cb1a7a0/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U=
gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
moul.io/http2curl/v2 v2.3.0 h1:9r3JfDzWPcbIklMOs2TnIFzDYvfAZvjeavG6EzP7jYs=
moul.io/http2curl/v2 v2.3.0/go.mod h1:RW4hyBjTWSYDOxapodpNEtX0g5Eb16sxklBqmd2RHcE=

78
api_file/jwtSet/jwt.go Normal file
View File

@ -0,0 +1,78 @@
package jwtSet
//
//import (
// "github.com/iris-contrib/middleware/jwt"
// "github.com/sirupsen/logrus"
// "main/database"
// "main/model"
// "main/utils"
// "time"
//)
//
//var Jwt *jwt.Middleware
//var keys model.JwtKeys
//
//func GetJwtKeys() model.JwtKeys {
// db := database.GetInstance().GetMysqlDb()
// if utils.DataIsNil(keys) || keys.Date != time.Now().Format("2006-01-02") {
// keys = model.JwtKeys{}
// if err := db.Where("date = ? and token = ''", time.Now().Format("2006-01-02")).First(&keys).Error; err != nil {
// logrus.Errorln("sql执行失败", err)
// return model.JwtKeys{}
// }
// }
// if keys.Key == "" {
// keys.Date = time.Now().Format("2006-01-02")
// keys.Key = utils.NewKey(32)
// if err := db.Create(&keys).Error; err != nil {
// logrus.Errorln("sql执行失败", err)
// return model.JwtKeys{}
// }
// }
// if !keys.Updated && !utils.DataIsNil(Jwt) {
// UpdateJwt()
// }
// return keys
//}
////func Init() {
//// if utils.DataIsNil(keys) {
//// GetJwtKeys()
//// }
//// Jwt = jwt.New(jwt.Config{
//// ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
//// return []byte(keys.Key), nil
//// },
//// ErrorHandler: func(context iris.Context, err error) {
//// if err == nil {
//// return
//// }
//// context.StopExecution()
//// context.StatusCode(iris.StatusUnauthorized)
//// context.SetErr(err)
//// },
//// Extractor: jwt.FromAuthHeader,
//// SigningMethod: jwt.SigningMethodHS256,
//// })
//// db := database.GetInstance().GetMysqlDb()
//// keys.Updated = true
//// if err := db.Updates(&keys).Error; err != nil {
//// logrus.Errorln("sql执行失败", err)
//// return
//// }
////}
//
//func UpdateJwt() {
// if utils.DataIsNil(keys) {
// GetJwtKeys()
// }
// Jwt.Config.ValidationKeyGetter = func(token *jwt.Token) (interface{}, error) {
// return []byte(keys.Key), nil
// }
// db := database.GetInstance().GetMysqlDb()
// keys.Updated = true
// if err := db.Updates(&keys).Error; err != nil {
// logrus.Errorln("sql执行失败", err)
// return
// }
//}

81
api_file/main.go Normal file
View File

@ -0,0 +1,81 @@
package main
import (
"fmt"
nested "github.com/antonfisher/nested-logrus-formatter"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/middleware/accesslog"
"github.com/sirupsen/logrus"
"main/config"
"main/database"
"main/service"
"main/utils"
"os"
"path"
"time"
)
func main() {
logrus.SetFormatter(&nested.Formatter{HideKeys: true, TimestampFormat: time.RFC3339})
//配置文件初始化
err := config.InitConfig(utils.GetEnvDefault("version", "dev"))
if err != nil {
logrus.Errorln("配置文件初始化失败:", err)
return
}
logrus.Infoln("配置文件初始化完成")
//日志初始化
ac := makeAccessLog()
//应用初始化
app := iris.New()
//应用ac-log
app.UseRouter(ac.Handler)
//错误处理
app.OnAnyErrorCode(handler)
//数据库连接初始化
if !database.GetInstance().InitDataPool() {
return
}
logrus.Infoln("数据库已连接")
//初始化用户信息,系统配置信息,菜单列表
utils.UpdateUserInfo()
utils.UpdateSysSettings()
logrus.Infoln("数据库结构初始化完成")
//jwtSet.Init()
//logrus.Infoln("jwt认证初始化完成")
//接口组
app.PartyFunc("/api", service.Apis)
logrus.Infoln("接口组配置完成")
//应用启动
logrus.Infoln("应用启动")
err = app.Run(iris.Addr(":8081"))
if err != nil {
return
}
}
// 生成acLog实例
func makeAccessLog() *accesslog.AccessLog {
cPath, _ := os.Getwd()
ac := accesslog.File(path.Join(cPath, config.Config.Logs.Log, fmt.Sprintf("access-%s.log", time.Now().Format("2006-01-02"))))
ac.AddOutput(os.Stdout)
ac.IP = true
ac.Delim = ' '
ac.ResponseBody = false
return ac
}
// 接口错误处理
func handler(ctx iris.Context) {
if ctx.GetErr() != nil {
err := ctx.JSON(utils.FormatRes(ctx.GetStatusCode(), ctx.GetErr().Error(), nil))
if err != nil {
return
}
} else {
err := ctx.JSON(utils.FormatRes(ctx.GetStatusCode(), "", nil))
if err != nil {
return
}
}
}

View File

@ -0,0 +1,12 @@
package model
import "gorm.io/gorm"
type BackgammonRoom struct {
RoomId int `json:"room_id"`
Player string `json:"player"`
Winner string `json:"winner"`
Current string `json:"current"`
PawnStatus string `json:"pawn_status"`
gorm.Model
}

19
api_file/model/balance.go Normal file
View File

@ -0,0 +1,19 @@
package model
import "gorm.io/gorm"
type Balances struct {
Username string `json:"username"`
Card string `json:"card"`
Type bool `gorm:"default:false" json:"type"` //1支出型0收入型
Balance float64 `json:"balance"`
gorm.Model
}
type BalanceLogs struct {
Username string
Card string
Date string
Balance float64
gorm.Model
}

28
api_file/model/chess.go Normal file
View File

@ -0,0 +1,28 @@
package model
import (
"gorm.io/gorm"
"time"
)
type ChessStatus struct {
gorm.Model
Players string `json:"players"`
Current string `json:"current"`
IsEnd bool `json:"is_end"`
Status string `json:"status"`
Winner string `json:"winner"`
ChessId string `json:"chess_id"`
}
type ChessStatusLog struct {
gorm.Model
RoomId uint `json:"roomId"`
Current string `json:"current"`
Players string `json:"players"`
IsEnd bool `json:"is_end"`
Status string `json:"status"`
Winner string `json:"winner"`
ChessId string `json:"chess_id"`
Time time.Time `json:"time"`
}

View File

@ -0,0 +1,9 @@
package model
import "gorm.io/gorm"
type RunningCrontab struct {
Name string
CronId int
gorm.Model
}

20
api_file/model/keys.go Normal file
View File

@ -0,0 +1,20 @@
package model
import "gorm.io/gorm"
// DayKeys 每天对应key表
type DayKeys struct {
Date string
Key string
AesKey string
User string
gorm.Model
}
type JwtKeys struct {
Username string
Date string
Key string
Token string
Updated bool `gorm:"default:false"`
gorm.Model
}

31
api_file/model/logs.go Normal file
View File

@ -0,0 +1,31 @@
package model
import "gorm.io/gorm"
// Logs 日志表
type Logs struct {
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Status string `json:"status,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Time string `json:"time,omitempty"`
Location string `json:"location,omitempty"`
Ip string `json:"ip,omitempty"`
gorm.Model
}
type LogFileDealLog struct {
Date string
Success bool
gorm.Model
}
// SysLogs 系统容器日志表
type SysLogs struct {
Time string `json:"time,omitempty"`
ContainerName string `json:"container_name,omitempty"`
ContainerImage string `json:"container_image,omitempty"`
Message string `json:"message,omitempty"`
Offset int `json:"offset,omitempty"`
gorm.Model
}

14
api_file/model/menus.go Normal file
View File

@ -0,0 +1,14 @@
package model
import "gorm.io/gorm"
type Menus struct {
MenuId string `json:"menu_id"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
RouteOnly bool `json:"route_only"`
UserType string `json:"user_type"`
WhiteList string `json:"white_list"`
gorm.Model
}

9
api_file/model/note.go Normal file
View File

@ -0,0 +1,9 @@
package model
import "gorm.io/gorm"
type UserNotes struct {
Username string `json:"username"`
Content string `json:"content"`
gorm.Model
}

18
api_file/model/sudoku.go Normal file
View File

@ -0,0 +1,18 @@
package model
import "gorm.io/gorm"
type Sudoku struct {
Sudoku string `json:"sudoku"`
Username string `json:"username"`
Result string `json:"result"`
gorm.Model
}
type SudokuStatus struct {
SudokuId uint `json:"sudoku_id"`
Username string `json:"username"`
Status string `json:"status"`
Complete bool `json:"complete"`
gorm.Model
}

View File

@ -0,0 +1,14 @@
package model
import (
"gorm.io/gorm"
"time"
)
type SysError struct {
Username string `json:"username"`
Time time.Time `json:"time"`
Function string `json:"function"`
ErrorInfo string `json:"error_info"`
gorm.Model
}

View File

@ -0,0 +1,17 @@
package model
import "gorm.io/gorm"
// SysIcons 系统图标库
type SysIcons struct {
Icon string `json:"icon"`
gorm.Model
}
type SysSettings struct {
Name string `json:"name"`
CnName string `json:"cn_name"`
Value string `json:"value"`
DType string `json:"d_type"`
gorm.Model
}

55
api_file/model/sysinfo.go Normal file
View File

@ -0,0 +1,55 @@
package model
import "gorm.io/gorm"
type SysInfo struct {
Date string `json:"date" gorm:"index:select_info"`
Datetime string `json:"datetime" gorm:"index:datetime_index"`
Username string `json:"username" gorm:"index:select_info"`
Hostname string `json:"hostname"`
Ip string `json:"ip" gorm:"index:select_info"`
SysVersion string `json:"sysVersion"`
PhysicalCount int `json:"physicalCount"`
LogicalCount int `json:"logicalCount"`
CpuPer float64 `json:"cpuPer"`
MemTotal string `json:"memTotal"`
MemUsed string `json:"memUsed"`
MemPer float64 `json:"memPer"`
DiskPoint string `json:"diskPoint"`
DiskTotal string `json:"diskTotal"`
DiskUsed string `json:"diskUsed"`
DiskPer string `json:"diskPer"`
NetSent int64 `json:"netSent"`
NetRec int64 `json:"netRec"`
SentSpeed string `json:"sentSpeed"`
RecSpeed string `json:"recSpeed"`
gorm.Model
}
type SysInfoOld struct {
Datetime string `json:"datetime" gorm:"index:datetime_index"`
Username string `json:"username"`
Hostname string `json:"hostname"`
Ip string `json:"ip"`
SysVersion string `json:"sysVersion"`
PhysicalCount int `json:"physicalCount"`
LogicalCount int `json:"logicalCount"`
CpuPer float64 `json:"cpuPer"`
MemTotal string `json:"memTotal"`
MemUsed string `json:"memUsed"`
MemPer float64 `json:"memPer"`
DiskPoint string `json:"diskPoint"`
DiskTotal string `json:"diskTotal"`
DiskUsed string `json:"diskUsed"`
DiskPer string `json:"diskPer"`
NetSent int64 `json:"netSent"`
NetRec int64 `json:"netRec"`
SentSpeed string `json:"sentSpeed"`
RecSpeed string `json:"recSpeed"`
}
type SysInfoUpdateLog struct {
Datetime string `json:"datetime"`
Update bool `json:"update"`
gorm.Model
}

38
api_file/model/user.go Normal file
View File

@ -0,0 +1,38 @@
package model
import "gorm.io/gorm"
// User 用户登录信息表
type User struct {
Username string
Password string
Date string
ConfirmCode string
gorm.Model
}
// Userinfo 用户信息表
type Userinfo struct {
Username string `json:"username"`
Avatar string `json:"avatar"`
Nickname string `json:"nickname"`
Mobile string `json:"mobile"`
Email string `json:"email"`
Location string `json:"location"`
Type string `json:"type"`
gorm.Model
}
// UserAction 用户行为表
type UserAction struct {
Username string
Action string
gorm.Model
}
type UserAutoLogin struct {
Username string
DeviceId string
Location string
gorm.Model
}

10
api_file/model/utils.go Normal file
View File

@ -0,0 +1,10 @@
package model
import "gorm.io/gorm"
// IpsLocation ip转地址表
type IpsLocation struct {
Ip string
Location string
gorm.Model
}

11
api_file/model/weather.go Normal file
View File

@ -0,0 +1,11 @@
package model
import "gorm.io/gorm"
// Weather 每日天气表
type Weather struct {
Date string
Location string
Weather string
gorm.Model
}

View File

@ -0,0 +1,319 @@
package api
import (
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"main/utils"
"mime/multipart"
"os"
"path"
"path/filepath"
"strings"
"time"
)
func getRootFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
userPath := fmt.Sprintf("./upload/%s", username.Username)
if !utils.FileIsExist(userPath) {
err := os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
var files filesRes
fileList, err := os.ReadDir(userPath)
if utils.ErrHandle(ctx, err) {
return
}
for _, file := range fileList {
if file.IsDir() {
files.Dirs = append(files.Dirs, file.Name())
} else {
var item fileItem
item.Name = file.Name()
f, err := os.Stat(path.Join(userPath, file.Name()))
if utils.ErrHandle(ctx, err) {
return
}
item.Size = f.Size()
item.Type = utils.GetFileType(f.Name())
files.Files = append(files.Files, item)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
if utils.ErrHandle(ctx, err) {
return
}
}
// 获取指定目录下文件
func getFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New(userPath + ":目录不存在"))
return
}
var files filesRes
fileList, err := os.ReadDir(userPath)
if utils.ErrHandle(ctx, err) {
return
}
for _, file := range fileList {
if file.IsDir() {
files.Dirs = append(files.Dirs, file.Name())
} else {
var item fileItem
item.Name = file.Name()
f, err := os.Stat(path.Join(userPath, file.Name()))
if utils.ErrHandle(ctx, err) {
return
}
item.Size = f.Size()
item.Type = utils.GetFileType(f.Name())
files.Files = append(files.Files, item)
}
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", files))
if utils.ErrHandle(ctx, err) {
return
}
}
// 删除文件或目录
func deleteFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("目录不存在"))
return
}
if info, _ := os.Stat(userPath); info.IsDir() {
err := os.RemoveAll(userPath)
if utils.ErrHandle(ctx, err) {
return
}
} else {
err := os.Remove(userPath)
if utils.ErrHandle(ctx, err) {
return
}
}
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 上传头像
func uploadAvatar(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
file, info, err := ctx.FormFile("file")
if utils.ErrHandle(ctx, err) {
return
}
defer func(file multipart.File) {
err = file.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(file)
userPath := fmt.Sprintf("./static/%s", username.Username)
if !utils.FileIsExist(userPath) {
err = os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
fileType := strings.Split(info.Filename, ".")[len(strings.Split(info.Filename, "."))-1]
avatarName := fmt.Sprintf("./static/%s/avatar-%s.%s", username.Username, time.Now().Format("2006-01-02"), fileType)
_, err = ctx.SaveFormFile(info, avatarName)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", avatarName[1:]))
if utils.ErrHandle(ctx, err) {
return
}
}
func uploadDir(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(errors.New("目录已存在"))
return
}
err := os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 上传文件
func uploadFile(ctx iris.Context) {
username := utils.GetLoginUser(ctx)
if utils.DataIsNil(username) {
return
}
filePath := ctx.Params().Get("path")
file, info, err := ctx.FormFile("file")
if utils.ErrHandle(ctx, err) {
return
}
defer func(file multipart.File) {
err = file.Close()
if utils.ErrHandle(ctx, err) {
return
}
}(file)
userPath := fmt.Sprintf("./upload/%s/%s", username.Username, filePath)
if !utils.FileIsExist(userPath) {
err = os.MkdirAll(userPath, 0755)
if utils.ErrHandle(ctx, err) {
return
}
}
_, err = ctx.SaveFormFile(info, fmt.Sprintf("./upload/%s/%s/%s", username.Username, filePath, info.Filename))
if utils.ErrHandle(ctx, err) {
return
}
err = ctx.JSON(utils.FormatRes(iris.StatusOK, "", "success"))
if utils.ErrHandle(ctx, err) {
return
}
}
// 文件下载转到nginx-upload目录
func downloadFile(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", userToken.Username, filePath)
if !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("文件不存在"))
return
}
if info, _ := os.Stat(userPath); info.IsDir() {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只可下载文件"))
return
}
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", userToken.Username, filePath))
ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
ctx.Recorder().Header().Add("Content-Disposition", "attachment")
ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
return
}
func getDownloadFileType(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
var res videoM3u8
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
username := userToken.Username
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
currentPath, _ := filepath.Split(filePath)
filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
res.Video = utils.GetFileType(userPath) == "video"
res.M3u8 = utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", res))
if err != nil {
return
}
return
}
func downloadVideo(ctx iris.Context) {
authToken := ctx.GetCookie("token")
activeTime := time.Now().Add(-2 * time.Hour)
var userToken model.JwtKeys
db := database.GetInstance().GetMysqlDb()
if err := db.Where("token = ? and created_at >= ?", authToken, activeTime).First(&userToken).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if utils.DataIsNil(userToken.Username) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("未登录"))
return
}
username := userToken.Username
filePath := ctx.Params().Get("path")
userPath := fmt.Sprintf("./upload/%s/%s", username, filePath)
currentPath, _ := filepath.Split(filePath)
filename := strings.TrimSuffix(path.Base(userPath), path.Ext(userPath))
//fmt.Println(filePath, currentPath, filename)
if path.Ext(userPath) != ".ts" && !utils.FileIsExist(userPath) {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("文件不存在"))
return
}
if info, err := os.Stat(userPath); err == nil && info.IsDir() {
ctx.StatusCode(iris.StatusBadRequest)
ctx.SetErr(errors.New("只可下载文件"))
return
}
if utils.GetFileType(userPath) == "video" && utils.FileIsExist(fmt.Sprintf("./upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename)) {
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload-video/%s/%s%s/%s.m3u8", username, currentPath, filename, filename))
} else if utils.GetFileType(userPath) == "video" {
ctx.Recorder().Header().Add("X-Accel-Redirect", fmt.Sprintf("/upload/%s/%s", username, filePath))
} else {
tsPath := fmt.Sprintf("./upload-video/%s/%s%s/%s.ts", username, currentPath, filename[:len(filename)-6], filename)
ctx.Recorder().Header().Add("X-Accel-Redirect", tsPath[1:])
}
ctx.Recorder().Header().Add("X-Accel-Charset", "utf-8")
ctx.Recorder().Header().Add("Content-Disposition", "attachment")
ctx.Recorder().Header().Add("Content-Type", "application/octet-stream; charset=utf-8")
return
}

View File

@ -0,0 +1,17 @@
package api
import (
"github.com/kataras/iris/v12"
)
func File(party iris.Party) {
party.Get("/upload", getRootFile)
party.Get("/upload/{path:path}", getFile)
party.Post("/upload/{path:path}", uploadDir)
party.Post("/upload-file/{path:path}", uploadFile)
party.Delete("/upload/{path:path}", deleteFile)
party.Post("/static/avatar", uploadAvatar)
party.Get("/download/{path:path}", downloadFile)
party.Get("/download-video-check/{path:path}", getDownloadFileType)
party.Get("/download-video/{path:path}", downloadVideo)
}

View File

@ -0,0 +1,13 @@
package api
import (
"github.com/kataras/iris/v12"
"main/utils"
)
func Apis(ctx iris.Context) {
err := ctx.JSON(utils.FormatRes(iris.StatusOK, "", "allFileApis"))
if err != nil {
return
}
}

View File

@ -0,0 +1,172 @@
package api
import "time"
// user-----------------------------------------------------------------------------------------------
type result struct {
Date string
Password string
ConfirmCode string
UpdatedAt time.Time
Key string
AesKey string
}
// weather---------------------------------------------------------------------------------------------
type resWeather struct {
Status int `json:"status"`
Message string `json:"message"`
Data resData `json:"data"`
}
type resData struct {
Forecast24h resDate `json:"forecast_24h"`
}
type resDate struct {
D0 res24h `json:"1"`
D1 res24h `json:"2"`
}
type res24h struct {
Time string `json:"time"`
MaxDegree string `json:"max_degree"`
MinDegree string `json:"min_degree"`
DayWeather string `json:"day_weather"`
DayWindDirection string `json:"day_wind_direction"`
DayWindPower string `json:"day_wind_power"`
NightWeather string `json:"night_weather"`
NightWindPower string `json:"night_wind_power"`
NightWindDirection string `json:"night_wind_direction"`
}
type resLocation struct {
Data map[string]string `json:"data"`
Message string `json:"message"`
Status int `json:"status"`
}
// backgammon-----------------------------------------------------------------------------------------------
type typeRoomStatus struct {
RoomId int `json:"room_id"`
Player string `json:"player"`
}
// file-----------------------------------------------------------------------------------------------------
type filesRes struct {
Dirs []string `json:"dirs"`
Files []fileItem `json:"files"`
}
type fileItem struct {
Name string `json:"name"`
Type string `json:"type"`
Size int64 `json:"size"`
}
type videoM3u8 struct {
Video bool `json:"video"`
M3u8 bool `json:"m3u8"`
}
// notes------------------------------------------------------------------------------------------------------
type noteParam struct {
ID uint `json:"id"`
Content string `json:"content"`
}
// sysInfo------------------------------------------------------------------------------------------------------
type resSysInfo struct {
Datetime string `json:"datetime"`
CpuPer float64 `json:"cpu_per"`
Mem resMem `json:"mem"`
Disk []resDisk `json:"disk"`
Net resNet `json:"net"`
}
type resMem struct {
MemTotal string `json:"mem_total"`
MemUsed string `json:"mem_used"`
MemPer float64 `json:"mem_per"`
}
type resDisk struct {
Point string `json:"point"`
Total string `json:"total"`
Used string `json:"used"`
Per float64 `json:"per"`
}
type resNet struct {
Sent string `json:"sent"`
Rec string `json:"rec"`
}
type resSystem struct {
Hostname string `json:"hostname"`
Ip string `json:"ip"`
}
type sysInfoIDs struct {
IDs []int `json:"ids"`
}
// yeb----------------------------------------------------------------------------------------------------------
type paramsBalance struct {
Card string `json:"card"`
Type bool `json:"type"`
Balance float64 `json:"balance"`
}
type paramSZBalance struct {
Card string `json:"card"`
Type bool `json:"type"` // 1-支出0-收入
Amount float64 `json:"amount"`
}
// 月余额
type dateLog struct {
Date string `json:"date"`
Duration string `json:"duration"`
Changes float64 `json:"changes"`
Balance float64 `json:"balance"`
Detail []cardLog `json:"detail"`
}
// 详情
type cardLog struct {
Card string `json:"card"`
Balance float64 `json:"balance"`
Changes float64 `json:"changes"`
}
// menus-----------------------------------------------------------------------------
type resMenu struct {
MenuId string `json:"menu_id"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
RouteOnly bool `json:"route_only"`
Detail []subMenu `json:"detail"`
}
type subMenu struct {
MenuId string `json:"menu_id"`
Name string `json:"name"`
Icon string `json:"icon"`
Path string `json:"path"`
RouteOnly bool `json:"route_only"`
}
type sysIconsParam struct {
Icons string `json:"icons"`
}
// sudoku-----------------------------------------------------------------------------
type resSudokuListType struct {
New []sudokuListType `json:"new"`
Starting []sudokuListType `json:"starting"`
Complete []sudokuListType `json:"complete"`
}
type sudokuListType struct {
Sudoku string `json:"sudoku"`
SudokuId uint `json:"sudokuId"`
Username string `json:"username"`
Status string `json:"status"`
Complete bool `json:"complete"`
Id uint `json:"id"`
}
type addSudokuParam struct {
Sudoku string `json:"sudoku"`
Result string `json:"result"`
}

11
api_file/service/init.go Normal file
View File

@ -0,0 +1,11 @@
package service
import (
"github.com/kataras/iris/v12"
"main/service/api"
)
func Apis(p iris.Party) {
p.Get("/", api.Apis)
p.PartyFunc("/file", api.File)
}

View File

@ -0,0 +1,17 @@
package utils
import (
"github.com/sirupsen/logrus"
"main/database"
"main/model"
)
var SysSettings []model.SysSettings
func UpdateSysSettings() {
db := database.GetInstance().GetMysqlDb()
if err := db.Order("name").Find(&SysSettings).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
logrus.Infoln("更新系统配置列表")
}

24
api_file/utils/type.d.go Normal file
View File

@ -0,0 +1,24 @@
package utils
// ResponseBean result结构
type ResponseBean struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type ResApiUtils struct {
Flag bool `json:"flag"`
Data interface{} `json:"data"`
Msg string `json:"msg"`
}
// ResSudoku sudoku --------------------------------------------------------------------
type ResSudoku struct {
Flag bool `json:"flag"`
Data resSudokuData
}
type resSudokuData struct {
Check bool `json:"check"`
Result string `json:"result"`
}

73
api_file/utils/user.go Normal file
View File

@ -0,0 +1,73 @@
package utils
import (
"errors"
"fmt"
"github.com/kataras/iris/v12"
"github.com/sirupsen/logrus"
"main/database"
"main/model"
"strings"
)
var UserList []model.Userinfo
// GetLoginUser 根据token获取用户,返回用户信息
func GetLoginUser(ctx iris.Context) model.Userinfo {
auth := ctx.GetHeader("Authorization")
fmt.Println(auth)
if auth == "" || !strings.Contains(auth, "Bearer") {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.SetErr(errors.New("未登录"))
logrus.Warningln("请求未携带token信息")
return model.Userinfo{}
}
var tokens []model.JwtKeys
db := database.GetInstance().GetMysqlDb()
fmt.Println(strings.Split(auth, " ")[1])
if err := db.Where("token = ?", strings.Split(auth, " ")[1]).Find(&tokens).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
if len(tokens) == 0 {
ctx.StatusCode(iris.StatusUnauthorized)
ctx.SetErr(errors.New("未登录"))
logrus.Warningln(auth, "token信息无效")
return model.Userinfo{}
} else {
return GetUserInfo(tokens[0].Username)
}
//foobar := auth.Claims.(jwt.MapClaims)
//for key, value := range foobar {
// if key == "username" {
// return GetUserInfo(value.(string))
// }
//}
//ctx.StatusCode(iris.StatusInternalServerError)
//ctx.SetErr(errors.New("系统错误,请联系管理员"))
//logrus.Errorln("token存在但获取用户信息失败")
//return model.Userinfo{}
}
// GetUserInfo 根据用户名获取用户信息,先更新本地数据
func GetUserInfo(username string) model.Userinfo {
if len(UserList) == 0 {
logrus.Warnln("暂存用户列表为空,刷新数据")
UpdateUserInfo()
}
for _, u := range UserList {
if u.Username == username {
return u
}
}
logrus.Warnln("未找到对应的用户信息")
return model.Userinfo{}
}
// UpdateUserInfo 更新当前用户信息
func UpdateUserInfo() {
db := database.GetInstance().GetMysqlDb()
if err := db.Find(&UserList).Error; err != nil {
logrus.Errorln("sql执行失败", err)
}
logrus.Infoln("刷新暂存用户列表")
}

235
api_file/utils/utils.go Normal file
View File

@ -0,0 +1,235 @@
package utils
import (
"bufio"
"encoding/json"
"fmt"
"github.com/kataras/iris/v12"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"io"
"main/database"
"main/model"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"reflect"
"regexp"
"runtime"
"strings"
"time"
"unsafe"
)
// FormatRes 格式化result
func FormatRes(code int, msg string, data interface{}) ResponseBean {
return ResponseBean{
Code: code,
Msg: msg,
Data: data,
}
}
// GetEnvDefault 获取带默认值环境变量
func GetEnvDefault(name string, defaultVal string) string {
val, ok := os.LookupEnv(name)
if ok {
return val
} else {
return defaultVal
}
}
// FileRead 读取文件,返回行列表
func FileRead(file string, condition bool) ([]string, error) {
f, err := os.Open(file)
var res []string
if err != nil {
return []string{}, err
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
return
}
}(f)
reader := bufio.NewReader(f)
for {
line, _, err := reader.ReadLine()
if err != nil {
break
}
if condition && len(line) > 1 {
res = append(res, string(line))
}
}
return res, nil
}
func SendEmail(receiver []string, subject string, content string, test bool) error {
var emailUrl string
if !test {
emailUrl = fmt.Sprintf("https://git-ylsa0.cn/api_django/send_email/?subject=%s&receivers=%s&content=%s", url.QueryEscape(subject), strings.Join(receiver, ";"), url.QueryEscape(content))
} else {
emailUrl = fmt.Sprintf("http://localhost:8000/api/send_email/?subject=%s&receivers=%s&content=%s", url.QueryEscape(subject), strings.Join(receiver, ";"), url.QueryEscape(content))
}
resp, err := http.Get(emailUrl)
fmt.Println(emailUrl)
if err != nil {
logrus.Errorln("连接send_email接口失败", err)
return err
}
defer func(Body io.ReadCloser) {
err = Body.Close()
if err != nil {
}
}(resp.Body)
body, _ := io.ReadAll(resp.Body)
var r ResApiUtils
//解析json结构
err = json.Unmarshal(body, &r)
if err != nil {
logrus.Errorln("send_email接口结果json解析失败", err)
return err
}
return nil
}
// DataIsNil 判断数据是否为空
func DataIsNil(arg interface{}) bool {
if reflect.ValueOf(arg).Kind().String() == "ptr" || reflect.ValueOf(arg).Kind().String() == "slice" {
if reflect.ValueOf(arg).IsValid() {
return true
}
} else {
if reflect.ValueOf(arg).IsZero() {
return true
}
}
return false
}
// ErrHandle 错误处理
func ErrHandle(ctx iris.Context, err error) bool {
if err != nil {
pc, _, _, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc).Name()
db := database.GetInstance().GetMysqlDb()
if err1 := db.Create(&model.SysError{
Username: GetLoginUser(ctx).Username,
Time: time.Now(),
Function: f,
ErrorInfo: err.Error(),
}); err1 != nil {
logrus.Errorln("sql执行失败", err1)
}
ctx.StatusCode(iris.StatusInternalServerError)
ctx.SetErr(err)
return true
}
return false
}
// NewKey 取n位随机数
func NewKey(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890()-+*/~"
var src = rand.NewSource(time.Now().UnixNano())
const (
// 6 bits to represent a letter index
letterIdBits = 6
// All 1-bits as many as letterIdBits
letterIdMask = 1<<letterIdBits - 1
letterIdMax = 63 / letterIdBits
)
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdMax letters!
for i, cache, remain := n-1, src.Int63(), letterIdMax; i >= 0; {
if remain == 0 {
cache, remain = src.Int63(), letterIdMax
}
if idx := int(cache & letterIdMask); idx < len(letters) {
b[i] = letters[idx]
i--
}
cache >>= letterIdBits
remain--
}
return *(*string)(unsafe.Pointer(&b))
}
// CheckListItem 判断item是否在list内
func CheckListItem[T comparable](data []T, item T) bool {
for _, value := range data {
if value == item {
return true
}
}
return false
}
// FileIsExist 判断路径是否存在
func FileIsExist(path string) bool {
if _, err := os.Stat(path); os.IsNotExist(err) {
return false
}
return true
}
// Round float取小数
func Round(num float64, n int32) float64 {
res, _ := decimal.NewFromFloat(num).Round(n).Float64()
return res
}
// GetFileType 获取文件类型
func GetFileType(f string) string {
fileSuffix := path.Ext(f)
fileSuffix = strings.ToLower(fileSuffix)
patternFileSuffix := fmt.Sprintf("^%s,|,%s,|,%s$|%s", fileSuffix, fileSuffix, fileSuffix, fileSuffix)
regFileSuffix := regexp.MustCompile(patternFileSuffix)
for _, v := range SysSettings {
if strings.HasPrefix(v.Name, "fileType:") && regFileSuffix.MatchString(v.Value) {
return strings.Split(v.Name, "fileType:")[1]
}
}
//switch fileSuffix {
//case ".png", ".jpg", ".jpeg", ".bmp", ".gif":
// return "image"
//case ".mp4", ".m2v", ".mkv", ".rmvb", ".avi", ".flv", ".mov", ".m4v", ".wmv", ".f4v":
// return "video"
//case ".mp3", ".wav", ".flac":
// return "audio"
//case ".zip", ".rar", ".7z":
// return "zip"
//}
return "doc"
}
// IntAbs 数字取绝对值
func IntAbs(i int) int {
if i < 0 {
return -i
} else {
return i
}
}
// Reverse 字符串反转
func Reverse(s string) string {
a := []rune(s)
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
return string(a)
}
func GetRequestIp(ctx iris.Context) string {
realIp := ctx.Request().Header.Get("X-Real-IP")
if realIp != "" {
return realIp
}
ip := ctx.RemoteAddr()
return ip
}