feat:added system baseInfo api

Dev
This commit is contained in:
wenjianzhang
2020-08-08 09:26:35 +08:00
committed by GitHub
11 changed files with 475 additions and 0 deletions
+12
View File
@@ -1,10 +1,12 @@
package monitor
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
"go-admin/tools"
"go-admin/tools/app"
"runtime"
)
@@ -16,6 +18,11 @@ const (
GB = 1024 * MB
)
// @Summary 系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/settings/serverInfo [get]
func ServerInfo(c *gin.Context) {
osDic := make(map[string]interface{}, 0)
@@ -25,6 +32,8 @@ func ServerInfo(c *gin.Context) {
osDic["compiler"] = runtime.Compiler
osDic["version"] = runtime.Version()
osDic["numGoroutine"] = runtime.NumGoroutine()
osDic["ip"] = tools.GetLocaHonst()
osDic["projectDir"] = tools.GetCurrentPath()
dis, _ := disk.Usage("/")
diskTotalGB := int(dis.Total) / GB
@@ -45,6 +54,9 @@ func ServerInfo(c *gin.Context) {
memDic["usage"] = memUsedPercent
cpuDic := make(map[string]interface{}, 0)
cpuDic["cpuInfo"],_ = cpu.Info()
percent,_ := cpu.Percent(0,false)
cpuDic["Percent"] = fmt.Sprintf("%.2f",percent[0])
cpuDic["cpuNum"], _ = cpu.Counts(false)
app.Custum(c, gin.H{
+66
View File
@@ -0,0 +1,66 @@
package public
import (
"encoding/base64"
"errors"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go-admin/pkg/utils"
"go-admin/tools/app"
"io/ioutil"
"fmt"
)
// @Summary 上传图片
// @Description 获取JSON
// @Tags 公共接口
// @Accept multipart/form-data
// @Param type query string true "type" (1:单图,2:多图, 3base64图片)
// @Param file formData file true "file"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/public/uploadFile [post]
func UploadFile(c *gin.Context) {
tag,_ := c.GetPostForm("type")
urlPerfix := fmt.Sprintf("http://%s/",c.Request.Host)
if tag == ""{
app.Error(c,200,errors.New(""),"缺少标识")
return
} else {
switch tag {
case "1": // 单图
files,err := c.FormFile("file")
if err != nil {
app.Error(c,200,errors.New(""),"图片不能为空")
return
}
// 上传文件至指定目录
guid := uuid.New().String()
singleFile := "static/uploadfile/" + guid + utils.GetExt(files.Filename)
_ = c.SaveUploadedFile(files, singleFile)
app.OK(c, urlPerfix + singleFile, "上传成功")
return
case "2": // 多图
files := c.Request.MultipartForm.File["file"]
multipartFile := make([]string, len(files))
for _, f := range files {
guid := uuid.New().String()
multipartFileName := "static/uploadfile/" + guid + utils.GetExt(f.Filename)
_ = c.SaveUploadedFile(f, multipartFileName)
multipartFile = append(multipartFile, urlPerfix + multipartFileName)
}
app.OK(c, multipartFile, "上传成功")
return
case "3": // base64
files,_ := c.GetPostForm("file")
ddd, _ := base64.StdEncoding.DecodeString(files)
guid := uuid.New().String()
_ = ioutil.WriteFile("static/uploadfile/" + guid+ ".jpg", ddd, 0666)
app.OK(c, urlPerfix + "static/uploadfile/" + guid+ ".jpg", "上传成功")
}
}
}
+66
View File
@@ -0,0 +1,66 @@
package system
import (
"errors"
"github.com/gin-gonic/gin"
"go-admin/models"
"go-admin/tools"
"go-admin/tools/app"
"fmt"
"strings"
)
// @Summary 查询系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/setting [get]
func QuerySetting(c *gin.Context) {
var s models.SysSetting
r,e := s.Query()
if r.Logo != "" {
if !strings.HasPrefix(r.Logo,"http") {
r.Logo = fmt.Sprintf("http://%s/%s",c.Request.Host,r.Logo)
}
}
tools.HasError(e, "查询失败", 500)
app.OK(c,r,"查询成功")
}
// @Summary 更新或提交系统信息
// @Description 获取JSON
// @Tags 系统信息
// @Param data body models.SysUser true "body"
// @Success 200 {string} string "{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string "{"code": -1, "message": "添加失败"}"
// @Router /api/v1/system/setting [post]
func CreateSetting(c *gin.Context) {
var s models.ResponseSystemConfig
if err := c.ShouldBind(&s);err != nil {
app.Error(c,200,errors.New("缺少必要参数"),"")
return
}
var sModel models.SysSetting
sModel.Logo = s.Logo
sModel.Name = s.Name
a,e := sModel.Update()
if e != nil {
app.Error(c,200,e,"")
return
}
if a.Logo != "" {
if !strings.HasPrefix(a.Logo,"http") {
a.Logo = fmt.Sprintf("http://%s/%s",c.Request.Host,a.Logo)
}
}
app.OK(c,a,"提交成功")
}
+1
View File
@@ -53,3 +53,4 @@ settings:
dbname: dbname
# 代码生成是使用前端代码存放位置,需要指定到src文件夹,相对路径
frontpath: ../go-admin-ui/src
>>>>>>> c396f318ef0649f7231b8ee7b2a70d26159c19c2
+39
View File
@@ -0,0 +1,39 @@
package models
import (
orm "go-admin/global"
)
type SysSetting struct {
SettingsId int `json:"settings_id" gorm:"primary_key;AUTO_INCREMENT"`
Name string `json:"name" gorm:"type:varchar(256);"`
Logo string `json:"logo" gorm:"type:varchar(256);"`
BaseModel
}
func (SysSetting) TableName() string {
return "sys_setting"
}
//查询
func (s *SysSetting) Query() (create SysSetting, err error) {
result := orm.Eloquent.Table("sys_setting").First(&create)
if result.Error != nil {
err = result.Error
return
}
return create,nil
}
//修改
func (s *SysSetting) Update() (update SysSetting, err error) {
if err = orm.Eloquent.Table("sys_setting").Model(&update).Updates(&s).Error; err != nil {
return
}
return
}
type ResponseSystemConfig struct {
Name string `json:"name" binding:"required"` // 名称
Logo string `json:"logo" binding:"required"` // 头像
}
+65
View File
@@ -0,0 +1,65 @@
package utils
import (
"io/ioutil"
"mime/multipart"
"os"
"path"
)
// 获取文件大小
func GetSize(f multipart.File) (int, error) {
content, err := ioutil.ReadAll(f)
return len(content), err
}
// 获取文件后缀
func GetExt(fileName string) string {
return path.Ext(fileName)
}
//检查文件是否存在
func CheckExist(src string) bool {
_, err := os.Stat(src)
return os.IsNotExist(err)
}
// 检查文件权限
func CheckPermission(src string) bool {
_, err := os.Stat(src)
return os.IsPermission(err)
}
//如果不存在则新建文件夹
func IsNotExistMkDir(src string) error {
if exist := CheckExist(src); exist == false {
if err := MkDir(src); err != nil {
return err
}
}
return nil
}
//新建文件夹
func MkDir(src string) error {
err := os.MkdirAll(src, os.ModePerm)
if err != nil {
return err
}
return nil
}
// 打开文件
func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
f, err := os.OpenFile(name, flag, perm)
if err != nil {
return nil, err
}
return f, nil
}
+42
View File
@@ -0,0 +1,42 @@
package utils
import (
"database/sql/driver"
"fmt"
"time"
)
// JSONTime format json time field by myself
type JSONTime struct {
time.Time
}
// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (t JSONTime) MarshalJSON() ([]byte, error) {
if (t == JSONTime{}) {
formatted := fmt.Sprintf("\"%s\"", "")
return []byte(formatted), nil
} else {
formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
return []byte(formatted), nil
}
}
// Value insert timestamp into mysql need this function.
func (t JSONTime) Value() (driver.Value, error) {
var zeroTime time.Time
if t.Time.UnixNano() == zeroTime.UnixNano() {
return nil, nil
}
return t.Time, nil
}
// Scan valueof time.Time
func (t *JSONTime) Scan(v interface{}) error {
value, ok := v.(time.Time)
if ok {
*t = JSONTime{Time: value}
return nil
}
return fmt.Errorf("can not convert %v to timestamp", v)
}
+55
View File
@@ -0,0 +1,55 @@
package utils
import (
"net/http"
"time"
)
// api结构体
type APIException struct {
Code int `json:"code"`
Success bool `json:"success"`
Msg string `json:"msg"`
Timestamp int64 `json:"timestamp"`
Result interface{} `json:"result"`
}
// 实现接口
func (e *APIException) Error() string {
return e.Msg
}
func newAPIException(code int,msg string,data interface{},success bool) *APIException {
return &APIException{
Code: code,
Success: success,
Msg: msg,
Timestamp: time.Now().Unix(),
Result: data,
}
}
// 500 错误处理
func ServerError() *APIException {
return newAPIException(http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError),nil,false)
}
// 404 错误
func NotFound() *APIException {
return newAPIException(http.StatusNotFound, http.StatusText(http.StatusNotFound),nil,false)
}
// 未知错误
func UnknownError(message string) *APIException {
return newAPIException(http.StatusForbidden, message,nil,false)
}
// 参数错误
func ParameterError(message string) *APIException {
return newAPIException(http.StatusBadRequest, message,nil,false)
}
// 授权错误
func AuthError(message string) *APIException {
return newAPIException(http.StatusBadRequest, message,nil,false)
}
// 200
func ResponseJson(message string,data interface{},success bool) *APIException {
return newAPIException(http.StatusOK,message,data,success)
}
+94
View File
@@ -0,0 +1,94 @@
package utils
import (
"crypto/md5"
"encoding/base64"
"encoding/hex"
uuid "github.com/satori/go.uuid"
"io/ioutil"
"os"
"strings"
"time"
)
func Hmac(data string) string {
h := md5.New()
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
func IsStringEmpty(str string) bool {
return strings.Trim(str, " ") == ""
}
func GetUUID() string {
u := uuid.NewV4()
return strings.ReplaceAll(u.String(),"-","")
}
func PathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return false
}
func Base64ToImage(imageBase64 string) ([]byte, error) {
image, err := base64.StdEncoding.DecodeString(imageBase64)
if err != nil {
return nil, err
}
return image, nil
}
func GetDirFiles(dir string) ([]string, error) {
dirList, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
filesRet := make([]string, 0)
for _, file := range dirList {
if file.IsDir() {
files, err := GetDirFiles(dir + string(os.PathSeparator) + file.Name())
if err != nil {
return nil, err
}
filesRet = append(filesRet, files...)
} else {
filesRet = append(filesRet, dir+string(os.PathSeparator)+file.Name())
}
}
return filesRet, nil
}
func GetCurrentTimeStamp() int64 {
return time.Now().UnixNano() / 1e6
}
//slice去重
func RemoveRepByMap(slc []string) []string {
result := []string{}
tempMap := map[string]byte{}
for _, e := range slc {
l := len(tempMap)
tempMap[e] = 0
if len(tempMap) != l {
result = append(result, e)
}
}
return result
}
+19
View File
@@ -6,6 +6,7 @@ import (
"github.com/swaggo/gin-swagger/swaggerFiles"
log2 "go-admin/apis/log"
"go-admin/apis/monitor"
"go-admin/apis/public"
"go-admin/apis/system"
"go-admin/apis/system/dict"
. "go-admin/apis/tools"
@@ -71,6 +72,9 @@ func sysNoCheckRoleRouter(r *gin.RouterGroup) {
registerSysTableRouter(v1)
registerPublicRouter(v1)
registerSysSettingRouter(v1)
}
func registerDBRouter(api *gin.RouterGroup) {
@@ -253,3 +257,18 @@ func registerDeptRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddlewar
dept.DELETE("/:id", system.DeleteDept)
}
}
func registerSysSettingRouter(v1 *gin.RouterGroup) {
setting := v1.Group("/setting")
{
setting.GET("", system.QuerySetting)
setting.POST("", system.CreateSetting)
setting.GET("/serverInfo",monitor.ServerInfo)
}
}
func registerPublicRouter(v1 *gin.RouterGroup) {
p := v1.Group("/public")
{
p.POST("/uploadFile", public.UploadFile)
}
}
+16
View File
@@ -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)
}