新增系统设置接口
This commit is contained in:
commit
389d2970c0
150 files changed
+21555
No files matched your search
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
type Response struct {
|
||||
// 代码
|
||||
Code int `json:"code" example:"200"`
|
||||
// 数据集
|
||||
Data interface{} `json:"data"`
|
||||
// 消息
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
type Page struct {
|
||||
List interface{} `json:"list"`
|
||||
Count int `json:"count"`
|
||||
PageIndex int `json:"pageIndex"`
|
||||
PageSize int `json:"pageSize"`
|
||||
}
|
||||
|
||||
type PageResponse struct {
|
||||
// 代码
|
||||
Code int `json:"code" example:"200"`
|
||||
// 数据集
|
||||
Data Page `json:"data"`
|
||||
// 消息
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
func (res *Response) ReturnOK() *Response {
|
||||
res.Code = 200
|
||||
return res
|
||||
}
|
||||
|
||||
func (res *Response) ReturnError(code int) *Response {
|
||||
res.Code = code
|
||||
return res
|
||||
}
|
||||
|
||||
func (res *PageResponse) ReturnOK() *PageResponse {
|
||||
res.Code = 200
|
||||
return res
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package msg
|
||||
|
||||
var (
|
||||
CreatedSuccess = "创建成功!"
|
||||
UpdatedSuccess = "更新成功!"
|
||||
DeletedSuccess = "删除成功!"
|
||||
DeletedFail = "删除失败!"
|
||||
GetSuccess = "查询成功!"
|
||||
NotFound = "未找到相关内容或者数据为空!"
|
||||
)
|
||||
@@ -0,0 +1,44 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// 失败数据处理
|
||||
func Error(c *gin.Context, code int, err error, msg string) {
|
||||
var res Response
|
||||
res.Msg = err.Error()
|
||||
if msg != "" {
|
||||
res.Msg = msg
|
||||
}
|
||||
c.JSON(http.StatusOK, res.ReturnError(code))
|
||||
}
|
||||
|
||||
// 通常成功数据处理
|
||||
func OK(c *gin.Context, data interface{}, msg string) {
|
||||
var res Response
|
||||
res.Data = data
|
||||
if msg != "" {
|
||||
res.Msg = msg
|
||||
}
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// 分页数据处理
|
||||
func PageOK(c *gin.Context, result interface{}, count int, pageIndex int, pageSize int, msg string) {
|
||||
var res PageResponse
|
||||
res.Data.List = result
|
||||
res.Data.Count = count
|
||||
res.Data.PageIndex = pageIndex
|
||||
res.Data.PageSize = pageSize
|
||||
if msg != "" {
|
||||
res.Msg = msg
|
||||
}
|
||||
c.JSON(http.StatusOK, res.ReturnOK())
|
||||
}
|
||||
|
||||
// 兼容函数
|
||||
func Custum(c *gin.Context, data gin.H) {
|
||||
c.JSON(http.StatusOK, data)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package captcha
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/mojocn/base64Captcha"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
var store = base64Captcha.DefaultMemStore
|
||||
|
||||
//configJsonBody json request body.
|
||||
type configJsonBody struct {
|
||||
Id string
|
||||
CaptchaType string
|
||||
VerifyValue string
|
||||
DriverAudio *base64Captcha.DriverAudio
|
||||
DriverString *base64Captcha.DriverString
|
||||
DriverChinese *base64Captcha.DriverChinese
|
||||
DriverMath *base64Captcha.DriverMath
|
||||
DriverDigit *base64Captcha.DriverDigit
|
||||
}
|
||||
|
||||
func DriverStringFunc() (id, b64s string, err error) {
|
||||
e := configJsonBody{}
|
||||
e.Id = uuid.New().String()
|
||||
e.DriverString = base64Captcha.NewDriverString(46, 140, 2, 2, 4, "234567890abcdefghjkmnpqrstuvwxyz", &color.RGBA{240, 240, 246, 246}, []string{"wqy-microhei.ttc"})
|
||||
driver := e.DriverString.ConvertFonts()
|
||||
cap := base64Captcha.NewCaptcha(driver, store)
|
||||
return cap.Generate()
|
||||
}
|
||||
|
||||
func DriverDigitFunc() (id, b64s string, err error) {
|
||||
e := configJsonBody{}
|
||||
e.Id = uuid.New().String()
|
||||
e.DriverDigit = base64Captcha.DefaultDriverDigit
|
||||
driver := e.DriverDigit
|
||||
cap := base64Captcha.NewCaptcha(driver, store)
|
||||
return cap.Generate()
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Application struct {
|
||||
ReadTimeout int
|
||||
WriterTimeout int
|
||||
Host string
|
||||
Port string
|
||||
Name string
|
||||
JwtSecret string
|
||||
Mode string
|
||||
DemoMsg string
|
||||
EnableDP bool
|
||||
}
|
||||
|
||||
func InitApplication(cfg *viper.Viper) *Application {
|
||||
return &Application{
|
||||
ReadTimeout: cfg.GetInt("readTimeout"),
|
||||
WriterTimeout: cfg.GetInt("writerTimeout"),
|
||||
Host: cfg.GetString("host"),
|
||||
Port: cfg.GetString("port"),
|
||||
Name: cfg.GetString("name"),
|
||||
JwtSecret: cfg.GetString("jwtSecret"),
|
||||
Mode: cfg.GetString("mode"),
|
||||
DemoMsg: cfg.GetString("demoMsg"),
|
||||
EnableDP: cfg.GetBool("enabledp"),
|
||||
}
|
||||
}
|
||||
|
||||
var ApplicationConfig = new(Application)
|
||||
@@ -0,0 +1,84 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/spf13/viper"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 数据库配置项
|
||||
var cfgDatabase *viper.Viper
|
||||
|
||||
// 应用配置项
|
||||
var cfgApplication *viper.Viper
|
||||
|
||||
// Token配置项
|
||||
var cfgJwt *viper.Viper
|
||||
|
||||
// Log配置项
|
||||
var cfgLogger *viper.Viper
|
||||
|
||||
// Ssl配置项 非必须
|
||||
var cfgSsl *viper.Viper
|
||||
|
||||
// 代码生成配置项 非必须
|
||||
var cfgGen *viper.Viper
|
||||
|
||||
//载入配置文件
|
||||
func Setup(path string) {
|
||||
viper.SetConfigFile(path)
|
||||
content, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Fatal(fmt.Sprintf("Read config file fail: %s", err.Error()))
|
||||
}
|
||||
|
||||
//Replace environment variables
|
||||
err = viper.ReadConfig(strings.NewReader(os.ExpandEnv(string(content))))
|
||||
if err != nil {
|
||||
log.Fatal(fmt.Sprintf("Parse config file fail: %s", err.Error()))
|
||||
}
|
||||
|
||||
cfgDatabase = viper.Sub("settings.database")
|
||||
if cfgDatabase == nil {
|
||||
panic("No found settings.database in the configuration")
|
||||
}
|
||||
DatabaseConfig = InitDatabase(cfgDatabase)
|
||||
|
||||
cfgApplication = viper.Sub("settings.application")
|
||||
if cfgApplication == nil {
|
||||
panic("No found settings.application in the configuration")
|
||||
}
|
||||
ApplicationConfig = InitApplication(cfgApplication)
|
||||
|
||||
cfgJwt = viper.Sub("settings.jwt")
|
||||
if cfgJwt == nil {
|
||||
panic("No found settings.jwt in the configuration")
|
||||
}
|
||||
JwtConfig = InitJwt(cfgJwt)
|
||||
|
||||
cfgLogger = viper.Sub("settings.logger")
|
||||
if cfgLogger == nil {
|
||||
panic("No found settings.logger in the configuration")
|
||||
}
|
||||
LoggerConfig = InitLog(cfgLogger)
|
||||
|
||||
cfgSsl = viper.Sub("settings.ssl")
|
||||
if cfgSsl == nil {
|
||||
// Ssl不是系统强制要求的配置,默认可以不用配置,将设置为关闭状态
|
||||
fmt.Println("warning config not found settings.ssl in the configuration")
|
||||
SslConfig = new(Ssl)
|
||||
SslConfig.Enable = false
|
||||
} else {
|
||||
SslConfig = InitSsl(cfgSsl)
|
||||
}
|
||||
|
||||
cfgGen = viper.Sub("settings.gen")
|
||||
if cfgGen == nil {
|
||||
panic("No found settings.gen")
|
||||
}
|
||||
GenConfig = InitGen(cfgGen)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Database struct {
|
||||
Driver string
|
||||
Source string
|
||||
}
|
||||
|
||||
func InitDatabase(cfg *viper.Viper) *Database {
|
||||
|
||||
db := &Database{
|
||||
Driver: cfg.GetString("driver"),
|
||||
Source: cfg.GetString("source"),
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
var DatabaseConfig = new(Database)
|
||||
@@ -0,0 +1,17 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Gen struct {
|
||||
DBName string
|
||||
FrontPath string
|
||||
}
|
||||
|
||||
func InitGen(cfg *viper.Viper) *Gen {
|
||||
return &Gen{
|
||||
DBName: cfg.GetString("dbname"),
|
||||
FrontPath: cfg.GetString("frontpath"),
|
||||
}
|
||||
}
|
||||
|
||||
var GenConfig = new(Gen)
|
||||
@@ -0,0 +1,19 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Jwt struct {
|
||||
Secret string
|
||||
Timeout int64
|
||||
}
|
||||
|
||||
func InitJwt(cfg *viper.Viper) *Jwt {
|
||||
return &Jwt{
|
||||
Secret: cfg.GetString("secret"),
|
||||
Timeout: cfg.GetInt64("timeout"),
|
||||
}
|
||||
}
|
||||
|
||||
var JwtConfig = new(Jwt)
|
||||
@@ -0,0 +1,27 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Logger struct {
|
||||
Path string
|
||||
Level string
|
||||
Stdout bool
|
||||
EnabledBUS bool
|
||||
EnabledREQ bool
|
||||
EnabledDB bool
|
||||
EnabledJOB bool `default:"false"`
|
||||
}
|
||||
|
||||
func InitLog(cfg *viper.Viper) *Logger {
|
||||
return &Logger{
|
||||
Path: cfg.GetString("path"),
|
||||
Level: cfg.GetString("level"),
|
||||
Stdout: cfg.GetBool("stdout"),
|
||||
EnabledBUS: cfg.GetBool("enabledbus"),
|
||||
EnabledREQ: cfg.GetBool("enabledreq"),
|
||||
EnabledDB: cfg.GetBool("enableddb"),
|
||||
EnabledJOB: cfg.GetBool("enabledjob"),
|
||||
}
|
||||
}
|
||||
|
||||
var LoggerConfig = new(Logger)
|
||||
@@ -0,0 +1,21 @@
|
||||
package config
|
||||
|
||||
import "github.com/spf13/viper"
|
||||
|
||||
type Ssl struct {
|
||||
KeyStr string
|
||||
Pem string
|
||||
Enable bool
|
||||
Domain string
|
||||
}
|
||||
|
||||
func InitSsl(cfg *viper.Viper) *Ssl {
|
||||
return &Ssl{
|
||||
KeyStr: cfg.GetString("key"),
|
||||
Pem: cfg.GetString("pem"),
|
||||
Enable: cfg.GetBool("enable"),
|
||||
Domain: cfg.GetString("domain"),
|
||||
}
|
||||
}
|
||||
|
||||
var SslConfig = new(Ssl)
|
||||
@@ -0,0 +1,13 @@
|
||||
package tools
|
||||
|
||||
type (
|
||||
Mode string
|
||||
)
|
||||
|
||||
const (
|
||||
ModeDev Mode = "dev" //开发模式
|
||||
ModeTest Mode = "test" //测试模式
|
||||
ModeProd Mode = "prod" //生产模式
|
||||
Mysql = "mysql" //mysql数据库标识
|
||||
Sqlite = "sqlite3" //sqlite
|
||||
)
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func PathExists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func PathCreate(dir string) error {
|
||||
return os.MkdirAll(dir, os.ModePerm)
|
||||
}
|
||||
|
||||
func FileCreate(content bytes.Buffer, name string) {
|
||||
file, err := os.Create(name)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
file.WriteString(content.String())
|
||||
//for i := 0; i < len(content); i++ {
|
||||
// //写入byte的slice数据
|
||||
// file.Write(content)
|
||||
// //写入字符串
|
||||
// //
|
||||
//}
|
||||
file.Close()
|
||||
}
|
||||
|
||||
func PathRemove(name string) {
|
||||
err := os.RemoveAll(name)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
func FileRemove(name string) {
|
||||
err := os.Remove(name)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
func FileZip(dst, src string, notContPath string) (err error) {
|
||||
//创建准备写入的文件
|
||||
fw, err := os.Create(dst)
|
||||
defer fw.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 通过 fw 来创建 zip.Write
|
||||
zw := zip.NewWriter(fw)
|
||||
defer func() {
|
||||
// 检测一下是否成功关闭
|
||||
if err := zw.Close(); err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
}()
|
||||
return filepath.Walk(src, func(path string, fi os.FileInfo, errBack error) (err error) {
|
||||
if errBack != nil {
|
||||
return errBack
|
||||
}
|
||||
|
||||
fh, err := zip.FileInfoHeader(fi)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
fh.Name = strings.TrimPrefix(path, string(filepath.Separator))
|
||||
|
||||
if fi.IsDir() {
|
||||
fh.Name += "/"
|
||||
}
|
||||
fh.Name = strings.Replace(fh.Name, notContPath, "", -1)
|
||||
|
||||
w, err := zw.CreateHeader(fh)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !fh.Mode().IsRegular() {
|
||||
return nil
|
||||
}
|
||||
|
||||
fr, err := os.Open(path)
|
||||
defer fr.Close()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
n, err := io.Copy(w, fr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("成功压缩文件: %s, 共写入了 %d 个字符的数据\n", path, n)
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
type ReplaceHelper struct {
|
||||
Root string //路径
|
||||
OldText string //需要替换的文本
|
||||
NewText string //新的文本
|
||||
}
|
||||
|
||||
func (h *ReplaceHelper) DoWrok() error {
|
||||
|
||||
return filepath.Walk(h.Root, h.walkCallback)
|
||||
|
||||
}
|
||||
|
||||
func (h ReplaceHelper) walkCallback(path string, f os.FileInfo, err error) error {
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
if f.IsDir() {
|
||||
log.Println("DIR:", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
//文件类型需要进行过滤
|
||||
|
||||
buf, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
//err
|
||||
return err
|
||||
}
|
||||
content := string(buf)
|
||||
log.Printf("h.OldText: %s \n", h.OldText)
|
||||
log.Printf("h.NewText: %s \n", h.NewText)
|
||||
|
||||
//替换
|
||||
newContent := strings.Replace(content, h.OldText, h.NewText, -1)
|
||||
|
||||
//重新写入
|
||||
ioutil.WriteFile(path, []byte(newContent), 0)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package tools
|
||||
|
||||
import "strconv"
|
||||
|
||||
func Float64ToString(e float64) string {
|
||||
return strconv.FormatFloat(e, 'E', -1, 64)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package tools
|
||||
|
||||
import "strconv"
|
||||
|
||||
func IntToString(e int) string {
|
||||
return strconv.Itoa(e)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package tools
|
||||
|
||||
import "strconv"
|
||||
|
||||
func Int64ToString(e int64) string {
|
||||
return strconv.FormatInt(e, 10)
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// 获取外网ip地址
|
||||
func GetLocation(ip string) string {
|
||||
if ip == "127.0.0.1" || ip == "localhost" {
|
||||
return "内部IP"
|
||||
}
|
||||
resp, err := http.Get("https://restapi.amap.com/v3/ip?ip=" + ip + "&key=3fabc36c20379fbb9300c79b19d5d05e")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
s, err := ioutil.ReadAll(resp.Body)
|
||||
fmt.Printf(string(s))
|
||||
|
||||
m := make(map[string]string)
|
||||
|
||||
err = json.Unmarshal(s, &m)
|
||||
if err != nil {
|
||||
fmt.Println("Umarshal failed:", err)
|
||||
}
|
||||
if m["province"] == "" {
|
||||
return "未知位置"
|
||||
}
|
||||
return m["province"] + "-" + m["city"]
|
||||
}
|
||||
|
||||
// 获取局域网ip地址
|
||||
func GetLocaHonst() string {
|
||||
netInterfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
fmt.Println("net.Interfaces failed, err:", err.Error())
|
||||
}
|
||||
|
||||
for i := 0; i < len(netInterfaces); i++ {
|
||||
if (netInterfaces[i].Flags & net.FlagUp) != 0 {
|
||||
addrs, _ := netInterfaces[i].Addrs()
|
||||
|
||||
for _, address := range addrs {
|
||||
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||
if ipnet.IP.To4() != nil {
|
||||
return ipnet.IP.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
//获取当前路径,比如:E:/abc/data/test
|
||||
func GetCurrentPath() string {
|
||||
dir, err := os.Getwd()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
return strings.Replace(dir, "\\", "/", -1)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"io/ioutil"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func StringToInt64(e string) (int64, error) {
|
||||
return strconv.ParseInt(e, 10, 64)
|
||||
}
|
||||
|
||||
func StringToInt(e string) (int, error) {
|
||||
return strconv.Atoi(e)
|
||||
}
|
||||
|
||||
func StringToBool(e string) (bool, error) {
|
||||
return strconv.ParseBool(e)
|
||||
}
|
||||
|
||||
func GetCurrentTimeStr() string {
|
||||
return time.Now().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
func GetCurrentTime() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func FormatTimeStr(timeStr string) (string, error) {
|
||||
loc, _ := time.LoadLocation("Local")
|
||||
theTime, err := time.ParseInLocation("2006-01-02T15:04:05.000Z", timeStr, loc)
|
||||
return theTime.Format("2006/01/02 15:04:05"), err
|
||||
}
|
||||
|
||||
func StructToJsonStr(e interface{}) (string, error) {
|
||||
if b, err := json.Marshal(e); err == nil {
|
||||
return string(b), err
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
func GetBodyString(c *gin.Context) (string, error) {
|
||||
body, err := ioutil.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
fmt.Printf("read body err, %v\n", err)
|
||||
return string(body), nil
|
||||
} else {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
func JsonStrToMap(e string) (map[string]interface{}, error) {
|
||||
var dict map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(e), &dict); err == nil {
|
||||
return dict, err
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
func StructToMap(data interface{}) (map[string]interface{}, error) {
|
||||
dataBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mapData := make(map[string]interface{})
|
||||
err = json.Unmarshal(dataBytes, &mapData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return mapData, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// 前景 背景 颜色
|
||||
// ---------------------------------------
|
||||
// 30 40 黑色
|
||||
// 31 41 红色
|
||||
// 32 42 绿色
|
||||
// 33 43 黄色
|
||||
// 34 44 蓝色
|
||||
// 35 45 紫红色
|
||||
// 36 46 青蓝色
|
||||
// 37 47 白色
|
||||
//
|
||||
// 代码 意义
|
||||
// -------------------------
|
||||
// 0 终端默认设置
|
||||
// 1 高亮显示
|
||||
// 4 使用下划线
|
||||
// 5 闪烁
|
||||
// 7 反白显示
|
||||
// 8 不可见
|
||||
|
||||
const (
|
||||
TextBlack = iota + 30
|
||||
TextRed
|
||||
TextGreen
|
||||
TextYellow
|
||||
TextBlue
|
||||
TextMagenta
|
||||
TextCyan
|
||||
TextWhite
|
||||
)
|
||||
|
||||
func Black(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextBlack)
|
||||
}
|
||||
|
||||
func Red(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextRed)
|
||||
}
|
||||
|
||||
func Green(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextGreen)
|
||||
}
|
||||
|
||||
func Yellow(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextYellow)
|
||||
}
|
||||
|
||||
func Blue(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextBlue)
|
||||
}
|
||||
|
||||
func Magenta(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextMagenta)
|
||||
}
|
||||
|
||||
func Cyan(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextCyan)
|
||||
}
|
||||
|
||||
func White(msg string) string {
|
||||
return SetColor(msg, 0, 0, TextWhite)
|
||||
}
|
||||
|
||||
func SetColor(msg string, conf, bg, text int) string {
|
||||
return fmt.Sprintf("%c[%d;%d;%dm%s%c[0m", 0x1B, conf, bg, text, msg, 0x1B)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//获取URL中批量id并解析
|
||||
func IdsStrToIdsIntGroup(key string, c *gin.Context) []int {
|
||||
return idsStrToIdsIntGroup(c.Param(key))
|
||||
}
|
||||
|
||||
func idsStrToIdsIntGroup(keys string) []int {
|
||||
IDS := make([]int, 0)
|
||||
ids := strings.Split(keys, ",")
|
||||
for i := 0; i < len(ids); i++ {
|
||||
ID, _ := StringToInt(ids[i])
|
||||
IDS = append(IDS, ID)
|
||||
}
|
||||
return IDS
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
jwt "go-admin/pkg/jwtauth"
|
||||
)
|
||||
|
||||
func ExtractClaims(c *gin.Context) jwt.MapClaims {
|
||||
claims, exists := c.Get("JWT_PAYLOAD")
|
||||
if !exists {
|
||||
return make(jwt.MapClaims)
|
||||
}
|
||||
|
||||
return claims.(jwt.MapClaims)
|
||||
}
|
||||
|
||||
func GetUserId(c *gin.Context) int {
|
||||
data := ExtractClaims(c)
|
||||
if data["identity"] != nil {
|
||||
return int((data["identity"]).(float64))
|
||||
}
|
||||
fmt.Println(GetCurrentTimeStr()+" [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserId 缺少identity")
|
||||
return 0
|
||||
}
|
||||
|
||||
func GetUserIdStr(c *gin.Context) string {
|
||||
data := ExtractClaims(c)
|
||||
if data["identity"] != nil {
|
||||
return Int64ToString(int64((data["identity"]).(float64)))
|
||||
}
|
||||
fmt.Println(GetCurrentTimeStr()+" [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetUserIdStr 缺少identity")
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetUserName(c *gin.Context) string {
|
||||
data := ExtractClaims(c)
|
||||
if data["nice"] != nil {
|
||||
return (data["nice"]).(string)
|
||||
}
|
||||
fmt.Println(GetCurrentTimeStr()+" [WARING] "+ c.Request.Method +" " + c.Request.URL.Path + " GetUserName 缺少nice")
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetRoleName(c *gin.Context) string {
|
||||
data := ExtractClaims(c)
|
||||
if data["rolekey"] != nil {
|
||||
return (data["rolekey"]).(string)
|
||||
}
|
||||
fmt.Println(GetCurrentTimeStr()+" [WARING] "+ c.Request.Method +" " + c.Request.URL.Path + " GetRoleName 缺少rolekey")
|
||||
return ""
|
||||
}
|
||||
|
||||
func GetRoleId(c *gin.Context) int {
|
||||
data := ExtractClaims(c)
|
||||
if data["roleid"] != nil {
|
||||
i := int((data["roleid"]).(float64))
|
||||
return i
|
||||
}
|
||||
fmt.Println(GetCurrentTimeStr()+" [WARING] " + c.Request.Method + " " + c.Request.URL.Path + " GetRoleId 缺少roleid")
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// 不建议使用的方法(即将过时)
|
||||
// Deprecated method (out of date)
|
||||
func StrToInt(err error, index string) int {
|
||||
result, err := strconv.Atoi(index)
|
||||
if err != nil {
|
||||
HasError(err, "string to int error"+err.Error(), -1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func CompareHashAndPassword(e string, p string) (bool, error) {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(e), []byte(p))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Assert 条件断言
|
||||
// 当断言条件为 假 时触发 panic
|
||||
// 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码
|
||||
func Assert(condition bool, msg string, code ...int) {
|
||||
if !condition {
|
||||
statusCode := 200
|
||||
if len(code) > 0 {
|
||||
statusCode = code[0]
|
||||
}
|
||||
panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
|
||||
}
|
||||
}
|
||||
|
||||
// HasError 错误断言
|
||||
// 当 error 不为 nil 时触发 panic
|
||||
// 对于当前请求不会再执行接下来的代码,并且返回指定格式的错误信息和错误码
|
||||
// 若 msg 为空,则默认为 error 中的内容
|
||||
func HasError(err error, msg string, code ...int) {
|
||||
if err != nil {
|
||||
statusCode := 200
|
||||
if len(code) > 0 {
|
||||
statusCode = code[0]
|
||||
}
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
panic("CustomError#" + strconv.Itoa(statusCode) + "#" + msg)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user