初始化项目文件

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

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
}