修改server db,添加跨域请求,修改登录请求与返回json数据

This commit is contained in:
junleea 2024-05-28 15:15:02 +08:00
parent 883d1e915a
commit 710ba85261
8 changed files with 91 additions and 53 deletions

View File

@ -8,7 +8,7 @@ import (
var DB *gorm.DB
func Init() {
dsn := "root:lj123456@tcp(127.0.0.1:3306)/video_t?charset=utf8mb4&parseTime=True&loc=Local"
dsn := "video_t:SDssrzALGiidPcjE@tcp(127.0.0.1:3306)/video_t?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {

32
handler/cross.go Normal file
View File

@ -0,0 +1,32 @@
package handler
import (
"github.com/gin-gonic/gin"
//"net/http"
)
//跨域访问cross origin resource share
func CrosHandler() gin.HandlerFunc {
return func(context *gin.Context) {
//method := context.Request.Method
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
context.Header("Access-Control-Max-Age", "172800")
context.Header("Access-Control-Allow-Credentials", "false")
context.Set("content-type", "application/json") //设置返回格式是json
// if method == "OPTIONS" {
// context.JSON(http.StatusOK, gin.H{
// "code":1,
// "message":"error",
// "data":"request error",
// })
// }
//处理请求
context.Next()
}
}

View File

@ -57,10 +57,10 @@ func DeleteDevice(c *gin.Context) {
if service.DeleteDevice(req.ID, int(id.(float64))) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}
@ -76,13 +76,13 @@ func UpdateDevice(c *gin.Context) {
"message": "success",
})
} else {
c.JSON(400, gin.H{
c.JSON(200, gin.H{
"code": 1,
"message": "failed",
})
}
} else {
c.JSON(400, gin.H{
c.JSON(200, gin.H{
"code": 1,
"message": "failed",
})
@ -96,11 +96,11 @@ func SetDeviceStatus(c *gin.Context) {
if service.SetDeviceStatus(req.Status, req.ID, int(id.(float64))) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}
@ -118,13 +118,13 @@ func AddDevice(c *gin.Context) {
"device_id": device_id,
})
} else {
c.JSON(400, gin.H{
c.JSON(200, gin.H{
"code": 1,
"message": "failed",
})
}
} else {
c.JSON(400, gin.H{
c.JSON(200, gin.H{
"code": 1,
"message": "failed",
})
@ -137,7 +137,7 @@ func GetDeviceList(c *gin.Context) {
c.JSON(200, gin.H{
"code": 0,
"message": "success",
"devices": devices,
"data": devices,
})
}
@ -150,11 +150,11 @@ func RestartDevice(c *gin.Context) {
if Restart(device.DeviceIP) {
c.JSON(200, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}
} else {
c.JSON(400, gin.H{"code": 1, "message": "failed"})
c.JSON(200, gin.H{"code": 1, "message": "failed"})
}
}

View File

@ -11,7 +11,7 @@ import (
"videoplayer/worker"
)
var signingKey = []byte("my_secret_key")
var signingKey = []byte("aadafcvretmoi9")
func SetUpUserGroup(router *gin.Engine) {
userGroup := router.Group("/user")
@ -20,15 +20,15 @@ func SetUpUserGroup(router *gin.Engine) {
}
type RLReq struct {
User string `json:"user"`
Email string `json:"email"`
Password string `json:"password"`
User string `json:"username" form:"username"`
Email string `json:"email" form:"email"`
Password string `json:"password" form:"password"`
}
func loginHandler(c *gin.Context) {
var req_data RLReq
tokenString := ""
if err := c.ShouldBindJSON(&req_data); err == nil {
if err := c.ShouldBind(&req_data); err == nil {
if len(req_data.Password) < 32 {
hasher := md5.New()
hasher.Write([]byte(req_data.Password)) // 生成密码的 MD5 散列值
@ -44,17 +44,22 @@ func loginHandler(c *gin.Context) {
})
tokenString, err = token.SignedString(signingKey)
if err != nil {
c.JSON(400, gin.H{"error": err.Error(), "code": 1, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": 1, "message": "error"})
return
}
worker.SetRedisWithExpire(tokenString, tokenString, time.Hour*10) // 设置过期时间为10分钟
// 返回令牌
c.JSON(200, gin.H{"code": 0, "message": "success", "token": tokenString})
data := make(map[string]interface{})
data["id"]= user.ID
data["username"]=user.Name
data["email"]=user.Email
data["token"] =tokenString
c.JSON(200, gin.H{"code": 0, "message": "success", "data":data})
} else {
c.JSON(400, gin.H{"error": "user not found", "code": 1, "message": "error"})
c.JSON(200, gin.H{"error": "user not found", "code": 1, "message": "error"})
}
} else {
c.JSON(400, gin.H{"error": err.Error(), "code": 1, "message": "error"})
c.JSON(200, gin.H{"error": err.Error(), "code": 1, "message": "error"})
}
}
@ -69,7 +74,7 @@ func registerHandler(c *gin.Context) {
req_data.Password = hex.EncodeToString(hasher.Sum(nil)) // 生成密码的 MD5 散列值
}
if service.ContainsUser(req_data.User, req_data.Email) == true {
c.JSON(400, gin.H{"error": "user already exists", "code": 1, "message": "error"})
c.JSON(200, gin.H{"error": "user already exists", "code": 1, "message": "error"})
return
}
id := service.CreateUser(req_data.User, req_data.Password, req_data.Email)
@ -81,10 +86,10 @@ func registerHandler(c *gin.Context) {
})
tokenString, err = token.SignedString(signingKey)
if err != nil {
c.JSON(400, gin.H{"error": err.Error()})
c.JSON(200, gin.H{"error": err.Error()})
}
} else {
c.JSON(400, gin.H{"error": err.Error()})
c.JSON(200, gin.H{"error": err.Error()})
}
fmt.Println(req_data)
worker.SetRedisWithExpire(tokenString, tokenString, time.Hour*10) // 设置过期时间为10分钟

View File

@ -85,15 +85,15 @@ func GetWillDelVideoList(c *gin.Context) {
func UpdateVideo(c *gin.Context) {
var video_req videoUpdateReq
user_id, _ := c.Get("id")
if err := c.ShouldBindJSON(&video_req); err == nil {
if err := c.ShouldBind(&video_req); err == nil {
res := service.UpdateVideo(video_req.VideoPath, video_req.VideoName, video_req.CameraID, video_req.ID, int(user_id.(float64)), video_req.Human, video_req.IsDelete, video_req.CreateTime, video_req.EndTime, video_req.FileSize)
if !res {
c.JSON(http.StatusBadRequest, gin.H{"error": "update video failed", "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": "update video failed", "code": 1, "message": "failed"})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
}
}
@ -107,7 +107,7 @@ func GetVideo(c *gin.Context) {
// 打开文件
file, err := os.Open(path + name)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
return
}
defer file.Close()
@ -120,57 +120,57 @@ func GetVideo(c *gin.Context) {
// 返回文件
c.JSON(http.StatusOK, gin.H{"message": "success", "code": 200})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "video is deleted"})
c.JSON(http.StatusOK, gin.H{"error": "video is deleted"})
}
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
c.JSON(http.StatusOK, gin.H{"error": err.Error()})
}
}
func CreateVideo(c *gin.Context) {
var video_req videoReq
user_id, _ := c.Get("id")
if err := c.ShouldBindJSON(&video_req); err == nil {
if err := c.ShouldBind(&video_req); err == nil {
fmt.Println(video_req)
id := service.CreateVideo(video_req.VideoPath, video_req.VideoName, video_req.CameraID, int(user_id.(float64)), video_req.Human, video_req.IsDelete, video_req.CreateTime, video_req.EndTime, video_req.FileSize)
if id == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "create video failed", "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": "create video failed", "code": 1, "message": "failed"})
return
}
c.JSON(http.StatusOK, gin.H{"id": id, "code": 0, "message": "success"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
}
}
func GetVideoList(c *gin.Context) {
var gvl_req gvlReq
id, _ := c.Get("id")
if err := c.ShouldBindJSON(&gvl_req); err == nil {
if err := c.ShouldBind(&gvl_req); err == nil {
videos := service.GetVideoList(int(id.(float64)), gvl_req.StartTime, gvl_req.EndTime)
c.JSON(http.StatusOK, gin.H{"videos": videos, "code": 0, "message": "success"})
c.JSON(http.StatusOK, gin.H{"data": videos, "code": 0, "message": "success"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
}
}
func DelayVideo(c *gin.Context) {
var delay_req delayReq
id, _ := c.Get("id")
if err := c.ShouldBindJSON(&delay_req); err == nil {
if err := c.ShouldBind(&delay_req); err == nil {
service.DelayVideo(delay_req.ID, int(id.(float64)), delay_req.Day)
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success"})
c.JSON(http.StatusOK, gin.H{"code": 0,"data":"延迟成功", "message": "success"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
}
}
func DeleteVideo(c *gin.Context) {
var video_req VideoDelReq
id, _ := c.Get("id")
if err := c.ShouldBindJSON(&video_req); err == nil {
if err := c.ShouldBind(&video_req); err == nil {
service.DeleteVideo(video_req.ID, int(id.(float64)))
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "success"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": 1, "message": "failed"})
}
}

21
main.go
View File

@ -9,13 +9,14 @@ import (
"videoplayer/worker"
)
var signingKey = []byte("my_secret_key")
var signingKey = []byte("aadafcvretmoi9")
func main() {
r := gin.Default()
dao.Init()
worker.InitRedis()
r.Use(handler.CrosHandler())
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
handler.SetUpVideoGroup(r)
handler.SetUpUserGroup(r)
@ -28,7 +29,7 @@ func main() {
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 从请求头中获取 JWT 令牌
tokenString := c.Request.Header.Get("Authorization")
tokenString := c.Request.Header.Get("token")
//请求方式为get时从url中获取token
if tokenString == "" {
@ -41,8 +42,8 @@ func JWTAuthMiddleware() gin.HandlerFunc {
return
}
if tokenString == "" {
c.AbortWithStatus(401)
c.JSON(401, gin.H{
//c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "Unauthorized",
"error": "token is empty",
"code": "3",
@ -52,9 +53,9 @@ func JWTAuthMiddleware() gin.HandlerFunc {
redisToken := worker.GetRedis(tokenString)
if redisToken == "" {
c.AbortWithStatus(401)
c.JSON(401, gin.H{
"message": "Unauthorized",
c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "server token is empty",
"code": "4",
})
@ -68,9 +69,9 @@ func JWTAuthMiddleware() gin.HandlerFunc {
// 验证令牌
if err != nil || !token.Valid {
c.AbortWithStatus(401)
c.JSON(401, gin.H{
"message": "Unauthorized",
c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "NOT_LOGIN",
"error": "Invalid token",
"code": "4",
})

BIN
videoplayer Executable file

Binary file not shown.

View File

@ -17,8 +17,8 @@ func InitRedis() {
// 连接redis
redisClient = redis.NewClient(&redis.Options{
Addr: "127.0.0.1:6379", // Redis 服务器地址
Password: "", // 如果 Redis 设置了密码
DB: 0, // 使用的数据库编号
Password: "lj502138", // 如果 Redis 设置了密码
DB: 2, // 使用的数据库编号
})
// 验证 Redis 客户端是否可以正常工作