添加日志记录表,日志记录代码

This commit is contained in:
junleea 2024-06-10 12:23:34 +08:00
parent d3946cee04
commit ca49391c2b
5 changed files with 47 additions and 6 deletions

View File

@ -27,6 +27,10 @@ func Init() {
if err != nil {
fmt.Println("device table:", err)
} // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
err = db.AutoMigrate(&Logger{})
if err != nil {
fmt.Println("logger table:", err)
} // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
DB = db
}

View File

@ -1,5 +1,22 @@
package dao
import "gorm.io/gorm"
type Logger struct {
ID uint `gorm:"primarykey"`
gorm.Model
Url string `gorm:"column:url"`
IP string `gorm:"column:ip"`
Method string `gorm:"column:method"`
Params string `gorm:"column:params"`
}
func InsertLogToDB(url, ip, method, params string) uint {
logger := Logger{Url: url, IP: ip, Method: method, Params: params}
DB.Create(&logger)
return logger.ID
}
func deleteByID(id int) bool {
DB.Where("ID = ?", id).Delete(&Logger{})
return true
}

View File

@ -113,7 +113,7 @@ func loginHandler(c *gin.Context) {
var req_data RLReq
tokenString := ""
if err := c.ShouldBind(&req_data); err == nil {
if len(req_data.Password) < 32 {
if len(req_data.Password) != 32 {
hasher := md5.New()
hasher.Write([]byte(req_data.Password)) // 生成密码的 MD5 散列值
req_data.Password = hex.EncodeToString(hasher.Sum(nil)) // 生成密码的 MD5 散列值
@ -161,7 +161,7 @@ func registerHandler(c *gin.Context) {
var req_data RLReq
tokenString := ""
if err := c.ShouldBindJSON(&req_data); err == nil {
if len(req_data.Password) < 32 {
if len(req_data.Password) != 32 {
hasher := md5.New()
hasher.Write([]byte(req_data.Password)) // 生成密码的 MD5 散列值
req_data.Password = hex.EncodeToString(hasher.Sum(nil)) // 生成密码的 MD5 散列值

19
main.go
View File

@ -27,13 +27,26 @@ func main() {
defer worker.CloseRedis()
}
func preDoRequest(c *gin.Context) {
fmt.Println(c.ClientIP())
func writeLogger(c *gin.Context) {
ip := c.ClientIP()
method := c.Request.Method
path := c.Request.URL.Path
params := ""
if method == "GET" {
params = c.Request.URL.RawQuery
}
if method == "POST" {
params = c.Request.PostForm.Encode()
}
res := dao.InsertLogToDB(path, ip, method, params)
if res == 0 {
fmt.Println("insert log failed")
}
}
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
preDoRequest(c)
go writeLogger(c)
// 从请求头中获取 JWT 令牌
tokenString := c.Request.Header.Get("token")

7
service/loggerService.go Normal file
View File

@ -0,0 +1,7 @@
package service
import "videoplayer/dao"
func insertLog(url, ip, method, params string) uint {
return dao.InsertLogToDB(url, ip, method, params)
}