update project path

This commit is contained in:
zhangwenjian committed 2020-03-18 23:09:37 +08:00
1 parent 26acdbd0d1
commit e027e6a259
76 files changed
+2562 -106

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/mojocn/base64Captcha"
"github.com/mssola/user_agent"
. "go-admin/models"
jwt "go-admin/pkg/jwtauth"
"go-admin/utils"
"log"
"net/http"
)
var store = base64Captcha.DefaultMemStore
func PayloadFunc(data interface{}) jwt.MapClaims {
if v, ok := data.(map[string]interface{}); ok {
u, _ := v["user"].(SysUser)
r, _ := v["role"].(SysRole)
return jwt.MapClaims{
jwt.IdentityKey: u.Id,
jwt.RoleIdKey: r.Id,
jwt.RoleKey: r.RoleKey,
jwt.NiceKey: u.Username,
jwt.DataScopeKey: r.DataScope,
jwt.RoleNameKey: r.Name,
}
}
return jwt.MapClaims{}
}
func IdentityHandler(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
return map[string]interface{}{
"IdentityKey": claims["identity"],
"UserName": claims["nice"],
"RoleKey": claims["rolekey"],
"UserId": claims["identity"],
"RoleIds": claims["roleid"],
"DataScope": claims["datascope"],
}
}
// @Summary 登陆
// @Description 获取token
// LoginHandler can be used by clients to get a jwt token.
// Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
// Reply will be of the form {"token": "TOKEN"}.
// @Accept application/json
// @Product application/json
// @Param username body models.Login true "Add account"
// @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
// @Router /login [post]
func Authenticator(c *gin.Context) (interface{}, error) {
var loginVals Login
var loginlog LoginLog
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
location := utils.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = utils.GetCurrntTime()
loginlog.CreateTime = utils.GetCurrntTime()
loginlog.Status = "0"
loginlog.IsDel = "0"
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginlog.Browser = browserName + " " + browserVersion
loginlog.Os = ua.OS()
loginlog.Msg = "登录成功"
loginlog.Platform = ua.Platform()
if err := c.ShouldBind(&loginVals); err != nil {
loginlog.Status = "1"
loginlog.Msg = "数据解析失败"
loginlog.UserName = loginVals.Username
loginlog.Create()
return nil, jwt.ErrMissingLoginValues
}
loginlog.UserName = loginVals.Username
if !store.Verify(loginVals.UUID, loginVals.Code, true) {
loginlog.Status = "1"
loginlog.Msg = "验证码错误"
loginlog.Create()
return nil, jwt.ErrInvalidVerificationode
}
user, role, e := loginVals.GetUser()
if e == nil {
loginlog.Create()
return map[string]interface{}{"user": user, "role": role}, nil
} else {
loginlog.Status = "1"
loginlog.Msg = "登录失败"
loginlog.Create()
log.Println(e.Error())
}
return nil, jwt.ErrFailedAuthentication
}
// @Summary 退出登录
// @Description 获取token
// LoginHandler can be used by clients to get a jwt token.
// Reply will be of the form {"token": "TOKEN"}.
// @Accept application/json
// @Product application/json
// @Success 200 {string} string "{"code": 200, "msg": "成功退出系统" }"
// @Router /logout [post]
// @Security
func LogOut(c *gin.Context) {
var loginlog LoginLog
ua := user_agent.New(c.Request.UserAgent())
loginlog.Ipaddr = c.ClientIP()
location := utils.GetLocation(c.ClientIP())
loginlog.LoginLocation = location
loginlog.LoginTime = utils.GetCurrntTime()
loginlog.CreateTime = utils.GetCurrntTime()
loginlog.Status = "0"
loginlog.IsDel = "0"
loginlog.Remark = c.Request.UserAgent()
browserName, browserVersion := ua.Browser()
loginlog.Browser = browserName + " " + browserVersion
loginlog.Os = ua.OS()
loginlog.Platform = ua.Platform()
loginlog.UserName = utils.GetUserName(c)
loginlog.Msg = "退出成功"
loginlog.Create()
c.JSON(http.StatusOK, gin.H{
"code": 200,
"msg": "退出成功",
})
}
func Authorizator(data interface{}, c *gin.Context) bool {
if v, ok := data.(map[string]interface{}); ok {
u, _ := v["user"].(SysUser)
r, _ := v["role"].(SysRole)
c.Set("role", r.Name)
c.Set("roleIds", r.Id)
c.Set("userId", u.Id)
c.Set("userName", u.UserName)
c.Set("dataScope", r.DataScope)
return true
}
return false
}
func Unauthorized(c *gin.Context, code int, message string) {
c.JSON(http.StatusOK, gin.H{
"code": code,
"msg": message,
})
}
+19
View File
@@ -0,0 +1,19 @@
package cronjob
import (
"github.com/robfig/cron/v3"
"log"
)
func TestJob(c *cron.Cron) {
id, err := c.AddFunc("1 * * * *", func() {
log.Println("Every hour on the one hour")
})
if err != nil {
log.Println(err)
log.Println("start error")
} else {
log.Println("Start Success; ID: %v", id)
}
}
+16
View File
@@ -0,0 +1,16 @@
package handler
import (
"github.com/gin-gonic/gin"
jwt "go-admin/pkg/jwtauth"
"log"
)
func NoFound(c *gin.Context) {
claims := jwt.ExtractClaims(c)
log.Printf("NoRoute claims: %#v\n", claims)
c.JSON(404, gin.H{
"code": "NOT_FOUND",
"message": "not found",
})
}
+22
View File
@@ -0,0 +1,22 @@
package handler
import (
"github.com/go-redis/redis"
"go-admin/config"
)
var RedisClient = new(redis.Client)
func init() {
RedisNewClient(config.RedisConnConfig.Addr, config.RedisConnConfig.Password, config.RedisConnConfig.DB)
}
func RedisNewClient(addr string, password string, db int) {
//timeout := time.Duration(readTimeout)
RedisClient = redis.NewClient(&redis.Options{
Addr: addr,
Password: password, // no password set
DB: db, // use default DB
//ReadTimeout: ,
})
}
+159
View File
@@ -0,0 +1,159 @@
package sd
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/load"
"github.com/shirou/gopsutil/mem"
"net/http"
"runtime"
"time"
)
const (
B = 1
KB = 1024 * B
MB = 1024 * KB
GB = 1024 * MB
)
// 健康状况
// @Summary 健康状况 HealthCheck shows OK as the ping-pong result.
// @Description 健康状况
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK"
// @Router /sd/health [get]
// @BasePath
func HealthCheck(c *gin.Context) {
message := "OK"
c.String(http.StatusOK, "\n"+message)
}
// @Summary 服务器硬盘使用量
// @Description 服务器硬盘使用量 DiskCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK - Free space: 16321MB (15GB) / 51200MB (50GB) | Used: 31%"
// @Failure 500 {string} string "CRITICAL"
// @Failure 429 {string} string "WARNING"
// @Router /sd/disk [get]
// @BasePath
func DiskCheck(c *gin.Context) {
u, _ := disk.Usage("/")
usedMB := int(u.Used) / MB
usedGB := int(u.Used) / GB
totalMB := int(u.Total) / MB
totalGB := int(u.Total) / GB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusOK
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
c.String(status, "\n"+message)
}
// @Summary OS
// @Description Os
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK - Free space: 455MB (0GB) / 8192MB (8GB) | Used: 5%"
// @Failure 500 {string} string "CRITICAL"
// @Failure 429 {string} string "WARNING"
// @Router /sd/os [get]
// @BasePath
func OSCheck(c *gin.Context) {
fmt.Println(runtime.GOOS) //取得操作系统版本
fmt.Println(runtime.Compiler) //取得编译器名称-gc
fmt.Println(runtime.NumCPU()) //取得CPU多核的数目
fmt.Println(runtime.Version())
status := http.StatusOK
c.String(status, runtime.GOOS+"/"+runtime.GOARCH+"/"+string(runtime.NumCPU()))
}
// @Summary CPU 使用量
// @Description CPU 使用量 DiskCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK - Load average: 2.39, 2.13, 1.97 | Cores: 2"
// @Failure 500 {string} string "CRITICAL"
// @Failure 429 {string} string "WARNING"
// @Router /sd/cpu [get]
// @BasePath
func CPUCheck(c *gin.Context) {
cores, _ := cpu.Counts(false)
cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true)
if err == nil {
for i, c := range cpus {
fmt.Printf("cpu%d : %f%%\n", i, c)
}
}
fmt.Println(c)
a, _ := load.Avg()
l1 := a.Load1
l5 := a.Load5
l15 := a.Load15
status := http.StatusOK
text := "OK"
if l5 >= float64(cores-1) {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if l5 >= float64(cores-2) {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Load average: %.2f, %.2f, %.2f | Cores: %d", text, l1, l5, l15, cores)
c.String(status, "\n"+message)
}
// @Summary 内存使用量
// @Description 内存使用量 RAMCheck checks the disk usage.
// @Accept text/html
// @Produce text/html
// @Success 200 {string} string "OK - Free space: 455MB (0GB) / 8192MB (8GB) | Used: 5%"
// @Failure 500 {string} string "CRITICAL"
// @Failure 429 {string} string "WARNING"
// @Router /sd/ram [get]
// @BasePath
func RAMCheck(c *gin.Context) {
u, _ := mem.VirtualMemory()
usedMB := int(u.Used) / MB
usedGB := int(u.Used) / GB
totalMB := int(u.Total) / MB
totalGB := int(u.Total) / GB
usedPercent := int(u.UsedPercent)
status := http.StatusOK
text := "OK"
if usedPercent >= 95 {
status = http.StatusInternalServerError
text = "CRITICAL"
} else if usedPercent >= 90 {
status = http.StatusTooManyRequests
text = "WARNING"
}
message := fmt.Sprintf("%s - Free space: %dMB (%dGB) / %dMB (%dGB) | Used: %d%%", text, usedMB, usedGB, totalMB, totalGB, usedPercent)
c.String(status, "\n"+message)
}