结构调整添加cmd

This commit is contained in:
zhangwenjian
2020-04-18 10:06:44 +08:00
parent f2829bfd98
commit a2f4c00246
72 changed files with 838 additions and 597 deletions
+46
View File
@@ -0,0 +1,46 @@
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
}
+9
View File
@@ -0,0 +1,9 @@
package msg
var (
CreatedSuccess = "创建成功!"
UpdatedSuccess = "更新成功!"
DeletedSuccess = "删除成功!"
GetSuccess = "查询成功!"
NotFound = "未找到相关内容或者数据为空!"
)
+44
View File
@@ -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)
}
+41
View File
@@ -0,0 +1,41 @@
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()
}
+31
View File
@@ -0,0 +1,31 @@
package config
import "github.com/spf13/viper"
type Application struct {
IsInit bool
ReadTimeout int
WriterTimeout int
Host string
Port string
Name string
JwtSecret string
Mode string
DemoMsg string
}
func InitApplication(cfg *viper.Viper) *Application {
return &Application{
IsInit: cfg.GetBool("isInit"),
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"),
}
}
var ApplicationConfig = new(Application)
+76
View File
@@ -0,0 +1,76 @@
package config
import (
"fmt"
"github.com/spf13/viper"
"io/ioutil"
"log"
"os"
"strings"
)
var cfgDatabase *viper.Viper
var cfgApplication *viper.Viper
var cfgJwt *viper.Viper
var cfgLog *viper.Viper
//func init() {
// InitConfig("settings.dev")
//}
//载入配置文件
func ConfigSetup(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()))
}
//}
//
//func InitConfig(fileName string) {
// viper.SetConfigName(fileName)
// viper.AddConfigPath("/config")
// err := viper.ReadInConfig()
// if err != nil {
// log.Println(err)
// }
cfgDatabase = viper.Sub("settings.database")
if cfgDatabase == nil {
panic("config not found settings.database")
}
DatabaseConfig = InitDatabase(cfgDatabase)
cfgApplication = viper.Sub("settings.application")
if cfgApplication == nil {
panic("config not found settings.application")
}
ApplicationConfig = InitApplication(cfgApplication)
cfgJwt = viper.Sub("settings.jwt")
if cfgJwt == nil {
panic("config not found settings.jwt")
}
JwtConfig = InitJwt(cfgJwt)
cfgLog = viper.Sub("settings.log")
if cfgLog == nil {
panic("config not found settings.log")
}
LogConfig = InitLog(cfgLog)
}
func SetApplicationIsInit() {
SetConfig("./config", "settings.application.isInit", false)
}
func SetConfig(configPath string, key string, value interface{}) {
viper.AddConfigPath(configPath)
viper.Set(key, value)
viper.WriteConfig()
}
+25
View File
@@ -0,0 +1,25 @@
package config
import "github.com/spf13/viper"
type Database struct {
Dbtype string
Host string
Port int
Name string
Username string
Password string
}
func InitDatabase(cfg *viper.Viper) *Database {
return &Database{
Port: cfg.GetInt("port"),
Dbtype: cfg.GetString("dbType"),
Host: cfg.GetString("host"),
Name: cfg.GetString("name"),
Username: cfg.GetString("username"),
Password: cfg.GetString("password"),
}
}
var DatabaseConfig = new(Database)
+19
View File
@@ -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)
+15
View File
@@ -0,0 +1,15 @@
package config
import "github.com/spf13/viper"
type Log struct {
Dir string
}
func InitLog(cfg *viper.Viper) *Log {
return &Log{
Dir: cfg.GetString("dir"),
}
}
var LogConfig = new(Log)
+13
View File
@@ -0,0 +1,13 @@
package tools
type (
Mode string
)
const (
ModeDev Mode = "dev" //开发模式
ModeTest Mode = "test" //测试模式
ModeProd Mode = "prod" //生产模式
Mysql = "mysql" //mysql数据库标识
Sqlite = "sqlite" //sqlite
)
+7
View File
@@ -0,0 +1,7 @@
package tools
import "strconv"
func Float64ToString(e float64) string {
return strconv.FormatFloat(e, 'E', -1, 64)
}
+7
View File
@@ -0,0 +1,7 @@
package tools
import "strconv"
func IntToString(e int) string {
return strconv.Itoa(e)
}
+7
View File
@@ -0,0 +1,7 @@
package tools
import "strconv"
func Int64ToString(e int64) string {
return strconv.FormatInt(e, 10)
}
+33
View File
@@ -0,0 +1,33 @@
package tools
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
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"]
}
+56
View File
@@ -0,0 +1,56 @@
package tools
import (
"errors"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"os"
"time"
)
func InitLogger() {
switch Mode(viper.GetString("settings.application.mode")) {
case ModeDev, ModeTest:
log.SetOutput(os.Stdout)
log.SetLevel(log.TraceLevel)
case ModeProd:
file, err := os.OpenFile(viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC, 0600)
if err != nil {
log.Fatal("log init failed")
}
var info os.FileInfo
info, err = file.Stat()
if err != nil {
log.Fatal(err)
}
fileWriter := logFileWriter{file, info.Size()}
log.SetOutput(&fileWriter)
log.SetLevel(log.ErrorLevel)
}
log.SetReportCaller(true)
}
type logFileWriter struct {
file *os.File
size int64
}
func (p *logFileWriter) Write(data []byte) (n int, err error) {
if p == nil {
return 0, errors.New("logFileWriter is nil")
}
if p.file == nil {
return 0, errors.New("file not opened")
}
n, e := p.file.Write(data)
p.size += int64(n)
//每天一个文件
if p.file.Name() != viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log" {
p.file.Close()
p.file, _ = os.OpenFile(viper.GetString("logger.dir")+"/api-"+time.Now().Format("2006-01-02")+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC, 0600)
p.size = 0
}
return n, e
}
+55
View File
@@ -0,0 +1,55 @@
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 GetCurrntTimeStr() string {
return time.Now().Format("2006/01/02 15:04:05")
}
func GetCurrntTime() time.Time {
return time.Now()
}
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
}
}
+22
View File
@@ -0,0 +1,22 @@
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
}
+62
View File
@@ -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("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 说明:缺少identity")
return 0
}
func GetUserIdStr(c *gin.Context) string {
data := ExtractClaims(c)
if data["identity"] != nil {
return Int64ToString(int64((data["identity"]).(float64)))
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少identity")
return ""
}
func GetUserName(c *gin.Context) string {
data := ExtractClaims(c)
if data["nice"] != nil {
return (data["nice"]).(string)
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少nice")
return ""
}
func GetRoleName(c *gin.Context) string {
data := ExtractClaims(c)
if data["rolekey"] != nil {
return (data["rolekey"]).(string)
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少rolekey")
return ""
}
func GetRoleId(c *gin.Context) int {
data := ExtractClaims(c)
if data["roleid"] != nil {
i := int((data["roleid"]).(float64))
return i
}
fmt.Println("****************************** 路径:" + c.Request.URL.Path + " 请求方法:" + c.Request.Method + " 缺少roleid")
return 0
}
+55
View File
@@ -0,0 +1,55 @@
package tools
import (
"golang.org/x/crypto/bcrypt"
"log"
"strconv"
)
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 {
log.Print(err.Error())
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("CustomErroe#" + 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)
}
}